检查类型为“0”的输入;复选框”;如果其值等于数组成员

Check an input of type "checkbox" if its value is equal to an array member?

本文关键字:如果 组成员 于数 复选框 输入 类型 检查      更新时间:2023-09-26

我正在尝试勾选与数组项具有相同值的框。我不知道如何只检查匹配的输入。通常要么全有要么全无。

JS

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

HTML

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

我是不是让这件事变得更难了?

试试看:

var arr = 'Comedy, Sports, Psychological'.split(', ');  
function inputShouldBeChecked() {
    $.each(arr, function (index, value) {          
        $("#genre input[value="+value+"]").prop("checked",true)
    });
}
$('button').click(inputShouldBeChecked);

DEMO

您不需要以下if条件,只需将其删除即可。

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