jquery: select input with given name and value

2019-04-18 11:22发布

问题:

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");

回答1:

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);


回答2:

No need for the comma. Try:

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


回答3:

Try with this

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


回答4:

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");


回答5:

<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');