user984003
user984003

Reputation: 29585

jquery: select input with given name and value

I want to check the input that is named weekday and has value = 1. I tried the line below. It checks all weekdays.

$('input[name = weekday], [value =1]').attr("checked", "checked");

Upvotes: 22

Views: 43537

Answers (5)

Adil
Adil

Reputation: 148178

Do not use comma to apply both conditions on same element.

$('input[name=weekday][value=1]').attr("checked", "checked");

As a side note you should use prop() instead of attr() for properties as suggested by jQuery doc and pointed by @tyleha.

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.

You can use .prop( propertyName, value ) to set the checked property as shown below.

$('input[name=weekday][value=1]').prop("checked", true);

Upvotes: 47

Amir Tofighi
Amir Tofighi

Reputation: 307

<input type="radio" name="some[thing]" value="one">
<input type="radio" name="some[thing]" value="two">
<input type="radio" name="some[thing]" value="three">
<input type="radio" name="some[thing]" value="four">
<input type="radio" name="some[thing]" value="five">
<input type="radio" name="some[thing]" value="six">

alert('1');
 $("input[value='four'][name='some\\[thing\\]']").attr("checked",true);
alert('2'); 
 $("input[value='four'][name='some\\[thing\\]']").attr("checked",false);
alert('3'); 

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129832

Comma separates multiple selectors, so you were searching for inputs named "weekday" and elements of any type with value = 1.

To combine both criteria in one selector, just add them after one another:

$('input[name=weekday][value=1]').attr("checked", "checked");

Upvotes: 1

GautamD31
GautamD31

Reputation: 28773

Try with this

$('input[name=weekday][value=1]').attr("checked", "checked");

Upvotes: 2

Darren
Darren

Reputation: 70814

No need for the comma. Try:

 var checked = $('input[name = weekday][value =1]').attr("checked", "checked");

Upvotes: 2

Related Questions