Disable radio buttons based on value
Asked Answered
F

2

7

I want to disable radio buttons based on the value of a variable. The radio that is equal to the variable value should be disabled.

Ex:

<input type="radio" name="r1" value="a" />Value a
<input type="radio" name="r1" value="b" />Value b

So if the $variable = 'a'; then the radio button which has the value a should be disabled.

Franko answered 17/9, 2011 at 10:52 Comment(1)
you can get the value by $('input[type="radio"]').val(); then set attribute disabled to trueAtahualpa
S
19

Try -

var a = 'a';
$("input[type=radio][value=" + a + "]").prop("disabled",true);

or

var a = 'a';
$("input[type=radio][value=" + a + "]").attr("disabled",true);

If you're using an older jQuery version.

Working demo - http://jsfiddle.net/FtwcL/1

Sisley answered 17/9, 2011 at 10:55 Comment(5)
Good one, but you should use prop for setting and getting properties that evaluate to a boolean value.Vesperal
@Vesperal - Am I right in thinking .prop will only work with post 1.6 versions of jQuery?Sisley
It works thanks but I want disabled to be added to the code like this <input type="radio" name="r1" value="a" disabled />Franko
@ipr101: Yes, but that's what the OP should be using either way.Vesperal
@Franko - jQuery adds the 'disabled' flag dynamically to the DOM so you won't see it in the code - if you viewed the souce code via something like Firebug you might see the 'disabled' flag added.Sisley
O
1

If you want to disable based by name and value, you can try this

var a = 'a';
var fieldName = 'r1';
$('input[type=radio][name=' + fieldName + '][value='+ a +']').prop('disabled', true);
Overreach answered 24/6, 2013 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.