Select a default radio button in angular 6 - javascript

I am new to Angular. Need some help here. There are two radio buttons for two text fields:
<div class="col-1">
<label class="radio-container mb-0 mt-1">
<input id="Page_Color" name="Page_Color" type="radio" [(ngModel)]='Br.Page_IsGraphic'
[value]='false' (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_IsGraphic','Page_GraphicName','Page_Color')">
<span class="checkmark"></span>
</label>
</div>
<div class="col-1">
<label class="radio-container mb-0 mt-1">
<input id="IsGraphic" name="IsGraphic" type="radio" (change)="updateRadioChangeValToObj('Page_IsGraphic','Page_Graphic','Page_GraphicName','PageColor')"
[(ngModel)]='Br.Page_IsGraphic' [value]='true'>
<span class="checkmark"></span>
</label>
</div>
In [(ngModel)]='Br.Page_IsGraphic' Br.Page_IsGraphic value is either true or false and that is dynamic and based on that the radio button is getting checked i think.
If it's true then the second radio button gets selected and if it's false then the 1st one.
Now the 1st text field had to be removed as per the requirement and I want the second radio button to be always selected by default.
Br.Page_IsGraphic value should be set to true before theis code gets executed for this to work? or is there another way.
I tried [checked]="true" and that did not work.

As I understand you have two radio button associated with two text field and want to show text fields based on radio buttons are checked or not
.html file
<input type="radio" [checked] = "isFirst === true" (change)="markFirst()"/> First
<input type="radio" [checked] = "isSecond === true" (change)="markSecond()"/>Second
<br><br>
<input type="text" placeholder="First" *ngIf="isFirst"/>
<br><br>
<input type="text" placeholder="Second" *ngIf="isSecond"/>
.ts file
export class AppComponent {
isFirst = false
isSecond = false
markFirst(){
this.isFirst = true
// this.isSecond = false If you want second to hide if one is shown
}
markSecond(){
this.isSecond = true
// this.isFirst = false If you want second to hide if one is shown
}
}
Working link
https://stackblitz.com/edit/angular-jkqvqz

I did this and it selected the checkbox by default:
[(ngModel)]='Br.Page_IsGraphic' [value]='Br.Page_IsGraphic'>

Related

jQuery radio button value is not changed on page load

I searched the net and tried all solutions for similar questions from SO, but just can't get this one working.
I am working in Django admin, and I have RadioSelect widget for the field is_valid, with two radio buttons in the form:
<div class="form-row field-is_valid">
<div>
<label for="id_is_valid_0">Is it valid?</label>
<ul id="id_is_valid" class="inline">
<li><label for="id_is_valid_0"><input type="radio" name="is_valid" value="True" id="id_is_valid_0" checked>
Yes
</label>
</li>
<li><label for="id_is_valid_1"><input type="radio" name="is_valid" value="False" id="id_is_valid_1">
No
</label>
</li>
</ul>
</div>
</div>
<div class="form-row field-not_valid_reason">
<div>
<label for="id_not_valid_reason">Reason:</label>
<select name="not_valid_reason" id="id_not_valid_reason">
<option value="" selected>Choose</option>
<option value="Expired">Expired</option>
<option value="Not adopted">Not adopted</option>
<option value="Unknown">Unknown</option>
</select>
</div>
</div>
I want to hide a class .field-not_valid_reason when 'Yes' (True) is checked (which is default for is_valid field) and show it when I click 'No'. This I accomplished.
Here is my jQuery code:
(function($) {
$(function() {
var isValid = $('input[type=radio][name=is_valid]'),
notValidReason = $('.field-not_valid_reason'),
function toggleFields(value) {
if (value === 'True') {
notValidReason.hide(250);
} else {
notValidReason.show(250);
}
}
// show/hide on load based on previous value of isValid
toggleFields(isValid.val());
// show/hide on change
isValid.change(function() {
toggleFields($(this).val());
alert(isValid.val());
});
});
})(django.jQuery);
But, for some reason, after the object is saved in the database with the is_valid field False, when I am on the change page of that object, the class .field-not_valid_reason is hidden, albeit active radio button is set to "No" (False).
Can you help, please?
In your current jquery code you where using alert(isValid.val()); to see which option is selected but this will give you first value only so to get current value which user has selected use $(this).val().
Then , onload you where getting right value for radio but the div was still hidden because you are again passing toggleFields(isValid.val()); which will give you first value only .So , to overcome this pass radio value which is checked i.e : $("input[name='is_valid']:checked").val() .

Angular 2/4 -- When binding a radio button [value] to an object or function, why does this reactive form value not update?

*NOTE: if anyone has a better way of doing this, I'm all ears.
I'm attempting to create a form with three radio buttons -- two with a static value, and one with a custom, user-generated value. Here's what's happening:
I have the default set to one:
When I click two, everything works as expected:
When I click the custom radio button, everything works as expected:
When I enter a value, the object correctly gets mutated, but the form value (which is set to one of the objects keys) doesn't update:
I can click back to two and get expected behavior:
And when I then click back to three, I see expected behavior:
Here's my code:
test.html
<form [formGroup]="myForm" novalidate>
<label for="every_fifteen_minutes">
<input id="two" type="radio" formControlName="test" value="one">
<span class="input_text">This [value] will always be one</span>
</label>
<label for="two">
<input id="two" type="radio" formControlName="test" value="two">
<span class="input_text">This [value] will always be two</span>
</label>
<label for="three">
<input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey">
<span>This [value] should be set to the input value:</span>
<input type="text" [(ngModel)]="myObj.strKey" [ngModelOptions]="{standalone: true}">
</label>
</form>
<div>this.myObj.str: {{getThat()}}</div>
<div>this: {{getThis()}}</div>
test.component.ts
myForm: any;
myObj: any = {
strKey: ""
}
private _buildForm() {
this.myForm = this.fb.group({
'test': ['1', Validators.required],
})
}
ngOnInit() {
this._buildForm();
}
getThat(): number {
return this.myForm.get('test').value
}
getThis(): string {
return this.myObj.strKey;
}
SO, my question is: why is the update not happening immediately, how can I get it to happen, and is it possible to do this in a less complicated way?
try add (input)="0" in
<input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey">
like this
<input id="three" type="radio" formControlName="test" [(value)]="myObj.strKey" (input)="0">

Use checkbox to clear/update radio buttons in html/angularjs

My form has a checkbox followed by several radio buttons.Basically, the design calls for a user to be able to use a checkbox to clear a set of radio buttons (or set a default value). If the user should select a radio button then the checkbox will also be set.
Overall most of the requirements are met by the code below, however there is one condition when it doesn't work:
User Selects Checkbox. (Check appears in checkbox)
User Selects Radio button. (Radio button is selected)
User Selects Checkbox Again. (Check disappears from checkbox and radio button deselects)
User Selects Radio button. (Check appears in checkbox and radio button selects)
User deselects Checkbox. (Check disappears but the value isn't updated so the radio button does not deselect)
What is happening? How can this be written to get the behavior my user wants?
Thanks,
Matt
Here is the code:
var myAngular=angular.module('myApp',[]);
myAngular.controller('myController',function($scope){
$scope.title="Angular Radio Buttons";
$scope.selectedValue='i10';
$scope.numStatus = 0;
$scope.numStatusChanged = function () {
console.log('numStatusChanged:')
if ($scope.numStatus === 0) {
$scope.numStatus = 3;
console.log('From 0 to 3.');
} else {
$scope.numStatus = 0;
console.log('From ' + $scope.numStatus + ' to 0.' )
}
};
$scope.$watch('numStatus', function(newValue,oldValue,scope){
console.log('newVal:' + newValue + ' oldValue:' + oldValue);
});
$scope.$watch('aBool', function(newValue,oldValue,scope){
console.log('aBoolNew:' + newValue + ' aBoolOld:' + oldValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller='myController'>
<p>Selected Value: {{numStatus}}</p>
<div class="checkBoxGroup">
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-checked="numStatus !== 0" ng-change="numStatusChanged()">
<label for="isCheckbox">A Value Is Selected</label>
<div class="radio-button-vertical">
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="1" name="numStatus" /> One</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="2" name="numStatus" /> Two</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="3" name="numStatus" /> Three</label>
</div>
</div>
</div>
</div>
</div>
You are using ngChecked and ngModel together, I would expect that your issue is that those two properties are conflicting with each other since they represent similar bindings (other SO post explaining this).
Just rewrite the checkbox to be:
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-change="numStatusChanged()">
and then do the numStatus !== 0 check in the numStatusChanged() method and use the result to set aBool.

Checked radio button

I need to know if a radio button has been selected to hide / show other options.
<input #r4 type="radio" name="x">
<span>Group</span>
<div class="subOption" *ngIf="r4.checked"></div>
div.subOption must be displayed when it has been selected.
it's correct?¿
I would just create a new boolean variable in the component, that you set as true when radio button has been checked. With that boolean you then display the div. So for example:
isChecked: boolean = false; // our new variable
<input type="radio" name="x" (click)="isChecked = true">
<div *ngIf="isChecked">
<!-- Your code here -->
</div>
EDIT: As to multiple radiobuttons... as mentioned in a comment, radio buttons seems at this point be kind of buggy with Angular. I have found the easiest way to deal with radio buttons seems to be using a form. So wrap your radio buttons in a form, like so:
<form #radioForm="ngForm">
<div *ngFor="let val of values">
<input (change)="changeValue(radioForm.value)" type="radio" [value]="val.id" name="name" ngModel />{{val.name}}
</div>
</form>
whereas on radio button would look like the following in this example:
{
id: 1,
name: 'value1'
}
In the form there is a change event, from which we pick up the chosen radio button value.
(change)="changeValue(radioForm.value)"
Then I would just play with boolean and the value chosen:
changeValue(val) {
this.valueChosen = true; // shows div
this.chosenVal = val.name; // here we have the value chosen
}
A plunker to play with: here

Angularjs input radio and ng-repeat issue

Okay so here is my setup i have the following array:
answers = [answer1, answer2]
with these i do the following:
<form>
<div class="col-xs-12" ng-repeat="answer in component.question.answers">
<div class="col-xs-1" style="width: 1%">
<div class="radio">
<label class="i-checks">
<input type="radio" name="a" ng-model="answer.is_correct">
<i></i>
</label>
</div>
</div>
<div class="col-xs-11">
<input type="text" ng-model="answer.answer" class="form-control" placeholder="Svar">
</div>
</div>
</form>
Now the input[radio] are inside the same form as they should. My goal is that when i set one as selected both of the answer objects should be updated so that only one of the object has the value is_correct = true
However what happens right now is that if i click the first and then second both values have is_correct = true
So what can i do?
Radio buttons are used to choose between different values for a single field or, in Angular's case, a single model. The logical solution would be to select the correct answer:
<input type="radio" ng-model="component.question.correctAnswer" ng-value="answer">
If you really need to set a flag you can easily achieve that with a watcher:
$scope.$watch('component.question.correctAnswer', function(correctAnswer) {
component.question.answers.forEach(function(answer) {
answer.is_correct = answer === correctAnswer ? true : false;
});
});

Categories