我试图勾选与数组项具有相同值的框。我无法弄清楚如何只检查匹配的输入。它通常全有或全无。
var arr = 'Comedy, Sports, Psychological'.split(', ');
function inputShouldBeChecked() {
$.each(arr, function (index, value) {
if ( value.toLowerCase() === $('#genre input[type=checkbox]').val().toLowerCase() ) {
// it's not possible to get the input as a $(this), is it?
$('#genre input[value='+ value +']').prop('checked', true); //???
}
});
}
$('button').click(inputShouldBeChecked);
<button>Check Genre</button>
<ul id="genre">
<li>
<input type="checkbox" name="genre-name" value="Sports" />
Sports
</li>
<li>
<input type="checkbox" name="genre-name" value="Comedy" />
Comedy
</li>
<li>
<input type="checkbox" name="genre-name" value="Action" />
Action
</li>
</ul>
我是否比实际需要更难?
答案 0 :(得分:2)
试一试:
var arr = 'Comedy, Sports, Psychological'.split(', ');
function inputShouldBeChecked() {
$.each(arr, function (index, value) {
$("#genre input[value="+value+"]").prop("checked",true)
});
}
$('button').click(inputShouldBeChecked);
<强> DEMO 强>
答案 1 :(得分:1)
如果条件不满意,请不要删除它。
if ( value.toLowerCase() === $('#genre input[type=checkbox]').val().toLowerCase() )
$(function() {
// Handler for .ready() called.
var arr = 'Comedy, Sports, Psychological'.split(', ');
function inputShouldBeChecked() {
$.each(arr, function(index, value) {
$('#genre input[value=' + value + ']').prop('checked', true);
});
}
$('button').click(inputShouldBeChecked);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Check Genre</button>
<ul id="genre">
<li>
<input type="checkbox" name="genre-name" value="Sports" />Sports
</li>
<li>
<input type="checkbox" name="genre-name" value="Comedy" />Comedy
</li>
<li>
<input type="checkbox" name="genre-name" value="Action" />Action
</li>
</ul>
&#13;