even that I see very many similar questions in this site, no one of them answer to my question.
So pleas, don't be angry with me that I discuss this subject again.
I work in durandal project, I have html pages with javascript files behind.
I have two radio button in one of the pages.
I want their "checked" attribute to be binding to a variable in the view-model behind.
It is looked simple... but it is not!
I try two ways, any one of them didn't succeed:
first-way: in the html:
<input type="radio"
name="radSearchBy"
id="byNo"
data-bind:"checked:isId" />
in javascript:
isId: ko.observable(true)
second-way: in the html:
in javascript:
isId: ko.observable("checked")
I know what is the problem.
even if I simply write
<input type="radio"
name="radSearchBy"
id="byNo"
data-bind:"checked:true" />
or:
<input type="radio"
name="radSearchBy"
id="byNo"
checked="checked" />
it doesn't work.
only whem I write:
<input type="radio"
name="radSearchBy"
id="byNo"
**checked** />
yes, the "checked" word without anything follow- it works well.
but it is problem, becouse how can I do it *binding?*
please help me as quick as you can.
Unfortunately, the answer is a bit complicated. Radio buttons match the value of your observable to the value attribute of the radio button. In the boolean case, it is impossible to handle simply because HTML will return 'true' or 'false' as strings, not as booleans.
The solution requires AFAIK computed observables:
HTML
<input type="radio"
name="radSearchBy"
value="true"
data-bind="checked: value" />True
<input type="radio"
name="radSearchBy"
value="false"
data-bind="checked: value" />False
JavaScript
radSearchBy = ko.observable(true);
value = ko.computed({
read: function() { return radSearchBy.toString(); },
write: function(val) { radSearchBy(val === 'true'); }
});
Related
I'm having a little problem with some radio buttons inside my form. I know that a checkbox could do this in a real easy way but, you know, customer asking for this.
So, this is the form part:
<label>
<span>Acconsento*</span>
<input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" ng-required="!ctrl.isValidPrivacy()"/>
</label>
<label>
<span>Non acconsento</span>
<input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1"/>
</label>
With respective JS part:
self.isValidPrivacy = function () {
return (!self.utente.privacy_1 || self.utente.privacy_1 == 0) ? false : true;
};
and ctrl.utente.privacy_1 must be == 1.
After trying ng-required="ctrl.utente.privacy_1 != 1"
or ng-required="!ctrl.utente.privacy_1 (removing value="0" from 2nd radio input) I still haven't found a way to accomplish this.
ctrl.utente.privacy_1 == 0 isn't shown as validation error, and it can't be selected by default (ctrl.utente.privacy_1 can't be false by default)
All others answers on StackOverflow doesn't solve my problem
Well, I think you have some messed concepts...
First, you don't need a ternary operator to discern between true and false, just return the result of the comparision:
return (!self.utente.privacy_1 || self.utente.privacy_1 == 0);
would be enough. That said, you don't even need a function to check for this, you could do it directly on the attribute, since it's a simple check:
<... ng-required="!$ctrl.utente.privacy_1 || $ctrl.utente.privacy_1 == 0" .../>
That said, I don't understand why do you need an ng-required at all, maybe you've missunderstood its meaning... ng-required it's used to force the user to give a value to an input field, is NOT for checking it's value, that is what it seems you're trying to do. If you want to be sure that the user selects one of the two options just use the html attribute 'required' on both inputs, and that's enough.
<label>
<span>Acconsento*</span>
<input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" required />
</label>
<label>
<span>Non acconsento</span>
<input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1" required />
</label>
I was looking to toggle a switch(also disable) using check box,and I came across html attributes checked/enabled, it works fine if I type it into the code it works well, but I am not able to figure out is how to control it dynamically using angularjs. I tried the code below for disabling I used
<input type="checkbox" value={{light.status}} ng-click="toggle(light.status)" enabled />
for checked I used,
<input type="checkbox" value={{light.status}} ng-click="toggle(light.status)" checked/>
I tried
<input type="checkbox" value={{light.status}} ng-click="toggle(light.status)" {{status}}/>
angular part of the same
function toggelingtype(type){
if(type==1}$scope.status="checked";
if(type==2) $scope.status="";
if(type==3)$scope.status="disabled;
this function is called when some http request I received
Simply use attributes like ng-checked and ng-disabled
<input type="checkbox" ng-checked="light.checked" ng-disabled="light.disabled" />
EDIT: Alternative
<input type="checkbox" ng-model="light.status" ng-disabled="!light.status" />
Now if you set light.status = false;, the checkbox will be both unchecked and disabled.
Hope it helps.
I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});
Got 2 radio buttons. If the second one is selected a div with a group of checkboxses is shown. In that case one of the checkboxses needs to be selected. But if the first radio button is selected then the div with the checkboxses isn't visibile but the validation messages is shown anyway.
<script>
webshims.setOptions('wspopover', { appendTo: 'body' });
$.webshims.activeLang("sv");
$.webshims.setOptions('forms', {
replaceValidationUI: true,
addValidators: true,
customMessages: true
});
$.webshims.setOptions('forms-ext', {
replaceUI: true
});
$.webshims.polyfill('forms forms-ext');
</script>
<input id="PersonOrCostDiv1" class="user-success" type="radio" required="" value="1" name="Level" data-cacheval="false">
<input type="radio" id="PersonOrCostDiv2" name="Level" required="" value="2" data-cacheval="false" class="user-success">
<input type="checkbox" data-dependent-validation='{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}' value="100000001" id="checkbox-group100000001" class="group-required user-error" name="SelectedCostDivisions" aria-invalid="true">
<input type="checkbox" data-dependent-validation="'{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}' value="100000004" id="checkbox-group100000004" class="group-required user-error" name="SelectedCostDivisions" aria-invalid="true">
I've been testing with and without "from-prop" and had some looks on this page:
http://afarkas.github.io/webshim/demos/demos/webforms/4-webforms-custom-validity.html
Notice what I think is a bug. If I fill up the requierd properties and then choose 'test 3' in the special case in the button. The page is posted to server.
But if I as in the first case fills up the requierd values and then choose 'test1' I got an error message. If I then choose 'test 3' that should work the error message is still there.
And another thing is when I use the 'group-required' I cant manage to get the error message in the selected language. The other messages works as it should.
Yeah, there was a small bug in the data-dependent-validation rule. The reason is, that data-depnendent-validation isn't really a customValidity modifier but a general property modifier, which has to be executed even if the control is invalid by another rule. (in your case group-required). I have fixed this issue (https://github.com/aFarkas/webshim/commit/7f670cf7693ab03dfc86097bda0491faf57b00ea).
But you should do it a little bit different. Instead of using data-dependent-validation='{"from": "PersonOrCostDiv2", "prop": "required", "from-prop": "value:2"}', you should simply use: data-dependent-validation="PersonOrCostDiv2". This will automatically check if the control is checked and will disable/enable the form-controls. Your HTML would look something like this (much simpler!):
<form>
<input id="PersonOrCostDiv1" class="user-success" type="radio" required="" value="1" name="Level" data-cacheval="false">
<input type="radio" id="PersonOrCostDiv2" name="Level" required="" value="2" data-cacheval="false">
<fieldset data-dependent-validation="PersonOrCostDiv2">
<input type="checkbox" value="100000001" id="checkbox-group100000001" class="group-required" data-errormessage="Please check on this group" name="SelectedCostDivisions">
<input type="checkbox" value="100000004" id="checkbox-group100000004" name="SelectedCostDivisions">
</fieldset>
<input type="submit" />
</form>
In case you don't want to update to the fixed version (It may have some bugs, because it's not a stable tested build (Note this is only fixed in master branch not the main gh-pages branch), you should remove data-dependent-validation. And disable/enable the controls or the fieldset yourself with JS depending on the checkedness of PersonOrCostDiv1. In case you use filedset:disabled, you have to use $.prop(fieldset, 'disabled', true/false) to make it work in IE. see: http://jsfiddle.net/trixta/K6nn9/).
To change the errormessage you need to either set it descriptive using the data-errormessage attribute (see html above) or with the following JS code:
webshims.ready('form-validators', function(){
webshims.customErrorMessages['group-required'].sv = "you really have to check on of these controls";
});
Feel free to ask again, if this doesn't help.
I am trying to setup two sets of radio buttons that will function simultaneously. In other words whenever Male is checked on the top, I would like Male at the bottom to be automatically checked. (and vice versa) If user scrolls down and clicks female then the one at the top should be checked. No matter which radio the user clicks both radio sets should always have the same value checked. Please advise on the most practical way to accomplish this. My main focus is Javascript or Jquery but I have spent several hours trying to come up with something to no avail. Please advise. Thanks! :)
<div class="top">
<input type="radio" name="sex" value="Male" /> Male<br />
<input type="radio" name="sex" value="Female" checked="checked" /> Female<br />
</div>
<div>Random Content</div>
<div class="bottom">
<input type="radio" name="sex2" value="Male" /> Male<br />
<input type="radio" name="sex2" value="Female" checked="checked" /> Female<br />
</div>
Attach to the change event and selecting all other radio buttons which have the same beginning of the name and are of equal value but which are not the current one.
$("input[name^='sex']").change(function(){
var $otherRadioButtons = $("input[name^='sex'][value='" + this.value + "']").not(this);
$otherRadioButtons.prop('checked', $(this).prop('checked'));
});
The above is not using any clever caching of the selectors which you can add yourself.
Basically, whenever a radio button changes it's checked value the code will select all other radio buttons with the same value (male/female) which also start with the same name (sex????) and set their checked property to the same value as the current one.
I hope this makes sense. See a working demo below.
DEMO - Changing radio buttons in a set.
Edit
I just noticed.. I am using jquery 1.3.2 and upgrading isnt an option
at the moment. You don't happen to have a 1.3.2 alternative do you?
For jQuery version 1.3.2 use the attr method instead of the prop method:
$("input[name^='sex']").change(function(){
var $otherRadioButtons = $("input[name^='sex'][value='" + this.value + "']").not(this);
$otherRadioButtons.attr('checked', $(this).attr('checked'));
});
DEMO - Changing radio buttons in a set using jQuery 1.3.2.
Just add an onclick listener to both sets. Like this:
document.getElementById("male1").onclick=clickMale;
document.getElementById("male2").onclick=clickMale;
document.getElementById("female1").onclick=clickFemale;
document.getElementById("female2").onclick=clickFemale;
function clickMale(){
document.getElementById("male1").checked=true;
document.getElementById("male2").checked=true;
}
function clickFemale(){
document.getElementById("female1").checked=true;
document.getElementById("female2").checked=true;
}
And add IDs to the radio buttons ("male1", "male2", "female1", "female2")
Since you mentioned it, Zove's answer in jQuery would be something like this, if you prefer:
$("#male1").click(clickMale);
$("#male2").click(clickMale);
$("#female1").click(clickFemale);
$("#female2").click(clickFemale);
function clickMale(){
$("#male1").attr('checked', true);
$("#male1").attr('checked', true);
}
function clickFemale(){
$("#female1").attr('checked', true);
$("#female2").attr('checked', true);
}
You don't need jQuery for something this simple, but if you're using it elsewhere, it's best to be consistent.
It might make sense, to share a class for both male / female inputs, e.g. 'js-male' or 'js-female'). This saves some code. for instance you could do:
$('.js-male').change(function() {
$('.js-male').attr('checked', $(this).attr('checked'));
});
$('.js-female').change(function() {
$('.js-female').attr('checked', $(this).attr('checked'));
});
There might be more elegant ways to deal with the whole situation so. Do you really want the inputs to have different names ('male', 'male2'), which means that your server receives two different params? If you give both radio button groups the same names, only the value of the last one will be sent to the server, anyway, if you mirror the radio buttons anyway, this doesn't really matter.
Demo
Just change the location of your jQuery source and this will work right out of the box.
<html>
<head>
<script src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#male1, #male2").live("click", function(){
$("#male1").attr("checked", $("#male2").attr("checked"));
$("#male2").attr("checked", $("#male1").attr("checked"));
});
$("#female1, #female2").live("click", function(){
$("#female1").attr("checked", $("#female2").attr("checked"));
$("#female2").attr("checked", $("#female1").attr("checked"));
});
});
</script>
</head>
<body>
<div class="top">
<input id="male1" type="radio" name="sex" value="Male" /> Male<br />
<input id="female1" type="radio" name="sex" value="Female" checked="checked" /> Female<br />
</div>
<div>Random Content</div>
<div class="bottom">
<input id="male2" type="radio" name="sex2" value="Male" /> Male<br />
<input id="female2" type="radio" name="sex2" value="Female" checked="checked" /> Female<br />
</div>
</body>
</html>