Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable radio buttons based on value

Tags:

jquery

radio

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.

like image 477
Ajay Avatar asked Sep 17 '11 10:09

Ajay


People also ask

How do I disable radio buttons?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

How can I avoid multiple selected radio buttons?

To avoid having multiple radio buttons selected use the same name attribute. Radio buttons are normally presented in radio groups. Only one radio button in a group can be selected at the same time. The radio group must share the same name (the value of the name attribute) to be treated as a group.

Can you uncheck radio buttons?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true . When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked. Here is the HTML for the examples in this article.


2 Answers

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

like image 199
ipr101 Avatar answered Sep 19 '22 17:09

ipr101


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);
like image 20
sbarrat Avatar answered Sep 20 '22 17:09

sbarrat