I have two radio buttons on my HTML page for gender selection (M or F).
How to retrieve which button was clicked in my typescript file? Here's the code
<form>
<label> Gender </label>
<br>
<input type="radio" required name='gender' value='Male' [(ngModel)]='gender'>Male
<br>
<input type="radio" required name='gender' value='Female' [(ngModel)]='gender'>Female
<br>
<button id="signup" class="btn btn-primary" type="submit">Signup</button>
</form>
On clicking the button, I want to assign M or F to a string in my typescript file.
You code is correct. No need to change anything.
This is your template code.
<form (ngSubmit)="onSubmit()">
<label>Gender</label>
<input type="radio" required name='gender' value='Male' [(ngModel)]='gender'>Male
<input type="radio" required name='gender' value='Female' [(ngModel)]='gender'>Female
<button id="signup" type="submit">Signup</button>
</form>
In your .ts file,
export class TestComponent implements OnInit {
gender: string = "Male";
onSubmit() {
console.log(gender);
}
}
This will give you the selected gender value.
Because you have used two way binding. It updates the ngModel whenever the input changes.
you can retrieve which button click by add ngModelChange method
<label> Gender </label>
<br>
<input type="radio" required name='gender' value='Male' [(ngModel)]='gender' (ngModelChange)="youMethodName(gender)">Male
<br>
<input type="radio" required name='gender' value='Female' [(ngModel)]='gender' (ngModelChange)="youMethodName(gender)">Female
<br>
</div>
<button id="signup" class="btn btn-primary" type="submit" >Signup</button> </form>
in your ts file
youMethodName(model) {
console.log("TCL: youMethodName -> model", model)
}
Although, answer is already accepted. I want to give solution of this problem if you do not want to use Two way data binding. this way is useful for breaking down two way data binding. So, there is no need for [(ngModel)] . Complete Working Demo found here in StackBlitz Link
Your HTML ...
<form>
<fieldset id="group1">
<input type="radio" (change)="handleChange($event)" name="group1" value="Male"/>Male
<input type="radio" (change)="handleChange($event)" name="group1" value ="Female"/> Female
</fieldset>
<div *ngIf="_prevSelected"> {{ _prevSelected}} </div>
<button (click)="click()">Show</button>
<div *ngIf="clicked"> <span> selected value is {{_prevSelected}} </span></div>
</form>
Your class file is..
private _prevSelected: any;
clicked:boolean;
handleChange(evt) {
let target = evt.target;
if (target.checked) this._prevSelected = target.value;
}
click(){
this.clicked =true;
}
Related
I have the following code
<div>Yes or no?</div>
<input type="radio" id="Nein" name="isUsedFor [(ngValue)]="isNotUsedFor" [(ngModel)]="isNotUsedFor">
<label for="no">Nein</label><br>
<input type="radio" id="Ja" name="isUsedFor" [(ngValue)]="isUsedFor" [(ngModel)]="isUsedFor">
<label for="yes">Ja</label>
</div>
My problem is, when I click on Nein, then Ja will be selected and not the Nein, and when I click on Ja then the Nein will be selected.
Here for example I have clicked on Nein and Ja will be selected and when I submit, then Ja will be submitted.
Do you have a idea to solve my inconvenience?
Thank you in advance.
Here is my .ts file:
public isNotUsedFor: string = "Nein";
public isUsedFor: string = "Ja";
Demo
You should use one model for both input and give value to input elements.
<div>Yes or no?</div>
<input type="radio" id="Nein" name="isUsedFor" value="Nein" [(ngModel)]="isUsedFor"/>
<label for="no">Nein</label><br>
<input type="radio" id="Ja" name="isUsedFor" value="Ja" [(ngModel)]="isUsedFor"/>
<label for="yes">Ja</label>
<br>
{{isUsedFor}}
in component
isUsedFor: string = "Ja";
How can I keep a checkbox checked after it's displayed on button click? Is this possible? Here is a working snippet.
.html
<a href="#tab1success" data-toggle="tab">
<h5>
<button mat-button class="btn filter" (click)="changeSummary()">Summary</button>
</h5>
</a>
<div id="tab1success">
<div *ngIf="bool">
<label class="btn btn-light btn-filter" id="bttns">
<input type="checkbox" name="name1" autoComplete="off"> check1
</label>
<label class="btn btn-light btn-filter" id="bttns">
<input type="checkbox" name="name2" autoComplete="off"> check2
</label>
</div>
</div>
.ts
bool = false
changeSummary() {
if (!this.bool) {
this.bool = true;
}
else {
this.bool = false;
}
}
Thank you for your time!
change
<div *ngIf="bool">
by
<div [hidden]="!bool">
I recommend you to go for handling this scenario using Forms API, which will be cleaner way to do this, either use template driven or model driven form. Remember the value inside component and as soon as template disabled, binding will take care of displaying what you have inside model.
//Create formSet object which will be holding all radio button
formSet = {};
Html
//Assign `ngModel` to each of input
<label class="btn btn-light btn-filter" id="bttns">
<input type="checkbox" [(ngModel)]="formSet.name" name="name2" autoComplete="off"> check1
</label>
<label class="btn btn-light btn-filter" id="bttns">
<input type="checkbox" [(ngModel)]="formSet.name2" name="name2" autoComplete="off"> check2
</label>
Demo
I'm not offensive about the accepted answer, but I personally can't digest to keep something inside DOM tree which is not visible. *ngIf was suitable there, rather using forms would suffice the purpose here.
I have a button group in which I have tree inputs of type radio.
The reason I use these, is that in order to get the style template I have bought for my project working I must use the exact same elements.
The button group is controlling the size on a dynamic table, and I need an event fired when a button (input) is pressed
<div class="btn-group" data-toggle="buttons" (click)="pageSizechanged($event)" >
<label class="btn btn-success">
<input type="radio" name="options"> 10
</label>
<label class="btn btn-success">
<input type="radio" name="options"> 20
</label>
<label class="btn btn-success active">
<input type="radio" > 30
</label>
</div>
I am using Angular 2 so I have tried to bind the inputs with values (not shown) without luck...
Update
The answer marked as solved below only partially solved my problem as I could only press each input once. To solve this I did the following:
<div class="btn-group">
<label class="btn btn-success">
<input type="radio" style="display:none" value="10" (change)="pageSizechanged($event.target)" > 10
</label>
<label class="btn btn-success">
<input type="radio" style="display:none" value="20" (change)="pageSizechanged($event.target)"> 20
</label>
<label class="btn btn-success">
<input type="radio" value="30" style="display:none" (change)="pageSizechanged($event.target)"> 30
</label>
</div>
In the change event i pass the target along. I do this because i want to set checked to false:
pageSizechanged(target) {
this._pagesize = target.value;
target.checked = false;
...
}
Otherwise the inputs will remain checked and the change event will therefore not be fired. If someone have a better way to do this, please share :)
Not entirelly sure what you want to achieve, but if I understood correctly.
You can bind the radio buttons with ngModel and avoid the current click-events entirelly, and rather react to changes. The following template works, just define your tableSize variable in the component class.
<div class="btn-group">
<label class="btn btn-success">
<input type="radio" name="options" [(ngModel)]="tableSize" value="10"> 10
</label>
<label class="btn btn-success">
<input type="radio" name="options" [(ngModel)]="tableSize" value="20"> 20
</label>
<label class="btn btn-success active" >
<input type="radio" [(ngModel)]="tableSize" value="30"> 30
</label>
</div>
Current tableSize: {{tableSize}}
If you need an event, you can add a (change)="myFunc($event.target.value)" to the input tags as well.
I don't think radio inputs are currently well supported in angular2. (you seem to have to make your own component).
I have used them with a simple event handler on the (click) event, like so:
<label class="chart__controls__item" *ngFor="let choice of ['competitor','taxonomy']">
<input type="radio"
name="options"
(click)="selectedChoice = choice"
[checked]="choice === selectedChoice" >
No
</label>
<label>
<input type="radio"
name="options"
[checked]="choice === selectedChoice"
(click)="selectedChoice = choice >
Yes
</label>
So if we initialise with selectedChoice='Yes', the second radio button will be selected. The [checked] attribute makes sure the selected radio button is checked and the (click) directive triggers the model change.
I have a question about type of button. What data-calc-type means in this code?
<label for="x">x: </label><input id="x" type="number" placeholder="0"/>
<label for="y">y: </label><input id="y" type="number" placeholder="0"/>
<label for="z">z: </label><input id="z" type="number" placeholder="0"/>
<div id="calculations">
<button data-calc-type="area">Pole</button>
<button data-calc-type="circuit">Obwód</button>
<button data-calc-type="volume">Objetość</button>
</div>
<p>Wynik: <span id="result"></span></p>
The data-* attribute is very neat. It let you store data in it so you can refer to it with your script.
Exemple: You have many buttons in your page. All buttons do different action. Instead of calling many function you could call one function that deal with data attribue and process data accordingly.
if ($('#button_ID').attr('data-*') == "this attribute"){ //do something}
I'm trying to come up with a form comprised of radio buttons group where a user must select one of the options and if he doesn't there's a custom validity message.
So the logic will be:
A user forgets to select an option and the validity message shows up.
He goes back and selects any option to go proceed.
The problem is, the way things are it only goes ahead if the selected option is the one with the onclick event as shown below. If it isn't then the message will keep showing up.
I have tried to juggle around with the required, oninvalid and onclick thingies but to no avail. Any ideas?
Thanks!
<form>
<input type="radio" name="test" value="0" required oninvalid="this.setCustomValidity('Click me')" onclick="setCustomValidity('')">Zero<br>
<input type="radio" name="test" value="1" class="wrapper">One<br>
<input type="radio" name="test" value="2" class="wrapper">Two<br>
<input type="submit">
</form>
<form>
<input type="radio" id="test" name="test" value="0" oninvalid="this.setCustomValidity('Click me')" onclick="clearValidity();" required >Zero<br>
<input type="radio" name="test" value="1" onclick="clearValidity()" class="wrapper">One<br>
<input type="radio" name="test" value="2" onclick="clearValidity()" class="wrapper">Two<br>
<input type="submit">
</form>
<script>
function clearValidity()
{
document.getElementById('test').setCustomValidity('');
}
</script>
This can be written as a function to make it work on any type of <input>:
document.querySelectorAll('form *[data-custom-validity]').forEach(el => {
const firstInput = el.querySelector('input:first-of-type')
// set custom validity if first input is invalid
firstInput.addEventListener('invalid', () => firstInput.setCustomValidity(el.dataset.customValidity))
// listen on all inputs for a change
el.querySelectorAll('input').forEach(input =>
input.addEventListener('change', () => firstInput.setCustomValidity('')))
})
<form>
<div data-custom-validity="Click me.">
<input type="radio">
<input type="radio">
</div>
</form>
This worked for me, I'm leaving it here in case it helps anyone.
<div class="genero">
<input type="radio" name="radiogroup" oninvalid="setCustomValidity('Mensaje')" onchange="try{setCustomValidity('')}catch(e){}" value="M">Masculino
<input type="radio" name="radiogroup" oninvalid="setCustomValidity('Mensaje')" onchange="try{setCustomValidity('')}catch(e){}" value="F">Femenino
</div>