Knockout Js Radio Bindings not setting Value - javascript

Here is the documentation I'm looking at : Example Adding Radio Buttons
It says:
KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute
Which I have done in this: jsfiddle
self.radioValue = ko.observable(1);
and the HTML:
<input type="radio" name="teloremail" value="1" data-bind="checked: radioValue" />
For me, this doesn't automatically set the radio to checked
Any reason for this?

The type of the radio button node’s value attribute is string, so you need to store the value as string also in your observable:
self.radioValue = ko.observable("1");
Demo JSFiddle.
The example also uses a string: "almond".

Related

One item select not working on radio buttons in AngularJS

I'm using AngularJS and filter option. When I select an item in radio buttons, its getting right data.
<input ng-click="filter = !filter" ng-value="!filter" ng-checked="filter" type="radio" ng-model="ctrl.filter[category]" />
But I need allow one select in radio buttons and its not working. What's the problem? Thanks.
DEMO
To properly work, radio inputs need a name attribute. It should be the same for all radio of the groupe.
You also need to change the ng-model of the radio to store its value in a single property.
<input ng-click="filter = !filter" ng-value="category" name="wineCategory" ng-checked="filter" type="radio" ng-model="ctrl.filter" />
Finally you need to adapt your filter methods.
All the inputs in the Radio box group must have only one reference to an ng-model which is typically the value of the input.
So, your input markup would be
<input value="{{category}}" type="radio" ng-model="ctrl.filterCategory" />
Where the value = category would be red, while or champagne.
Now likewise your filter function would change to use the ng-model like this
function filterByCategory(wine) {
return (self.filterCategory === wine.category || self.filterCategory === "") ? 'show':'hide';
}
Working demo here.
http://jsfiddle.net/nah42h1c/2/

Binding the same model variable to radio buttons and input-text

I would like manage with AngularJS UI which allows to pick one of the options (displayed as radio buttons group) or a custom value typed in a input-text.
It should look like:
http://jsbin.com/foyujali/7/edit
Here is the code that you can see also in the link below:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<div ng-app="tagsApp" ng-controller="TagsCtrl">
<input type="radio" id="conversion_type_sale" ng-model="tag.conversion_type" value="sale"/>
<label for=conversion_type_sale>Sale</label>
<input type="radio" id="conversion_type_lead" ng-model="tag.conversion_type" value="lead"/>
<label for=conversion_type_lead>Lead</label>
<input type="radio" id="conversion_type_custom" ng-model="tag.conversion_type" value="{{tag.conversion_type_custom_value}}"/>
<input type="text" placeholder="Custom" ng-model="tag.conversion_type_custom_value" id="conversion_type_custom_value"/>
<p>
The choosen conversion type is: <strong>{{tag.conversion_type}}</strong>
</p>
</div>
And JS:
angular.module('tagsApp', []).
controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
});
I would prefer not to use ngChange directive so I just bind the value or ng-value (I tried both) to the model of the input-text. It doesn't work properly this way, but I suppose there is an elegant AngularJS solution. Any suggestions?
Thanks in advance!
P.S. Just to clarify - I want the following functionality: http://jsbin.com/foyujali/10/edit but I want to avoid using ngChange directive.
This is what you're looking for: http://jsfiddle.net/colares/shcv8e1h/2/
Explaning the behavior
By focusing on the text field, the radio on the left is selected and chosen value is updated regarding the value of the text field;
By focusing on radio on the left of the text field, the chosen value is updated according to what is in the text field as well;
By changing the value of the text field, the chosen value is also updated;
Finally, by focusing on any other label or radio, the custom value remains, while the chosen value is update regarding the selected option.
To do so, I had to use a few more things in custom option input:
ng-focus: when I click on the text field, it updates the chosen value regarding the text field;
ng-change: as I update the text field, the final value is also updated;
ng-model: to store the auxiliar variable customColor, which remains regardless of the selected value.
Remember, the ng-value is used to set the value of the radio (or an <option>) from a given expression when we select it. This makes the radio and input text "bound", because they have the same value.
You could use $scope.$watch and look for the change in your controller like so:
http://jsfiddle.net/2R6aN/
var app = angular.module('tagsApp',[]);
app.controller('TagsCtrl', function ($scope) {
$scope.tag = {conversion_type: 'lead'};
$scope.$watch('conversion_type_custom_value',function(new_val) {
if (new_val) {
$scope.tag.conversion_type = new_val;
}
});
});
$watch is best option. Also, Instead of using modelName in 1st parameter of $watch, you can create your own stuff(eg. watching length of input box) and do desired action on it with second parameter.

Checkbox irregularities with jQuery

Here's some html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
And here's some javascript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.
Why would a checkbox show unchecked even if checked="checked" was added to the html?
Use element properties rather than attributes to change their state via javascript
checkbox.prop('checked',(textbox.val()!="") );
From the jQuery docs on .attr() and .prop():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.
consider something like:
function doSomething(el) {
el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}
<form>
<input type="checkbox" name="check-123">
<input type="text" name="text-123" onchange="doSomething(this)">
</form>
I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:
checkbox.prop('checked',textbox.val()!="");//property
Note, the following is only necessary if you come across any browser related inconsistencies.
if(textbox.val()!="")
{
checkbox.attr('checked','checked');
}
else
{
checkbox.removeAttr('checked');
}

jQuery radio button "checked" attribute not firing

I'm trying to add text to a div based on which radio button a user checks, but it ends up firing the "else" block no matter which attribute is checked, and displaying "female" every time.
Please help!
<input type="radio" name="gender" class="gender" id="male" value="male">Male<br />
<input type="radio" name="gender" class="gender" id="female" value="female">Female<br />
$(".gender").change(function () {
if ($("#male").attr("checked")) {
$("#content").text("male");
}
else {
$("#content").text("female");
}
});
Use .prop('checked') rather than .attr('checked'). The latter is based on the HTML attribute which will always be false because it is not in the DOM. .prop can be used to check property changes that may not be visible in the DOM.
http://jsfiddle.net/Xxuh8/
Your code would have worked until jQuery 1.8 or lesser. http://jsfiddle.net/Dnd2L/
In latest versions .attr is for the attributes which was defined in the HTML and .prop is mapped to the properties of the element which is dynamic and returns the current value.
http://jsfiddle.net/Dnd2L/1/
More information about attr and prop - https://stackoverflow.com/a/5876747/297641
You don't particularly need an if since your radio buttons are grouped and no multiple choices are possible.
You might want to use this instead:
$(".gender").change(function () {
$("#content").text($(this).val());
});
JSFiddle: http://jsfiddle.net/3Lsg6/
or if your radios don't have a class use
$("input[name='gender'][checked='checked']").val();
to get the value of the checked radio. To change which is checked, put the value of the cbx you want checked in val() i.e., ...val("male");

How can I create mutually exclusive radio buttons with different names?

I have a few radio buttons that belong to the same category, but I want to name them differently and make them mutually exclusive. How do I do that? Based on the selected value, I do different actions, and I can't access them if they have the same name.
Why can't you access them if they have the same name? You can add IDs (you should), you can distinguish by value or just count them and use the n-th element.
You should give radiobuttons the same name to make the browser understand they are exclusive.
You could (but should not) hack around this, and give each object a different name. Then add an onSelect/onClick handler for each object, and when the event fires, "uncheck" the other buttons. This is dirty and should be avoided.
Radio buttons require the same name to be mutually exclusive. However, they can have different ID attribute values, if you want to manipulate them individually with JavaScript.
There are lots of ways to get the selected value with jQuery:
<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />
// value of checked input tag of type 'radio'
var selectedValue = $('input[type=radio]:checked').val();
// value of checked input tag having name of 'foo'
var selectedValue = $('input[name=foo]:checked').val();
// value of the first checked radio button, regardless of name
var selectedValue = $('input:checked').val();
If you have to change the name, you can access the DOM and it's elements through JavaScript.
<input type="checkbox" name="X" id="myElement" />
<script> document.getElementById('myElement').name = 'text'; </script>
http://www.w3schools.com/JS/js_ex_dom.asp

Categories