通过比较值来选中复选框

时间:2011-05-31 11:02:48

标签: javascript jquery jquery-selectors

我有以下复选框列表,它是从HTML格式的服务器生成的。我也有一个像以下Javascript数组。 我想循环遍历数组并根据每个复选框检查每个值。如果匹配,则选中该复选框。

我正在使用 jQuery 1.4。

<script>
//this array is a result of an Ajax call
var arrMonth = [ "November", "October", "December"];

//Loop through the array and check each element against the check box list
//if found, make the checkbox checked
jQuery.each(arrMonth, function( intIndex, objValue) {

        // script to check against the each checbox in the table ctl00_ContentPlaceHolder1_cbStudentTypeEdit

});

</script>

生成的复选框列表:

<table cellspacing="10" cellpadding="20" border="0" id=
  "ctl00_ContentPlaceHolder1_cbStudentTypeEdit">
    <tbody>
      <tr>
        <td><span idkey="1"><input type="checkbox" tabindex="3" name=
        "ctl00$ContentPlaceHolder1$cbStudentTypeEdit$0" id=
        "ctl00_ContentPlaceHolder1_cbStudentTypeEdit_0" />
        <label for="ctl00_ContentPlaceHolder1_cbStudentTypeEdit_0">October</label></span></td>

        <td><span idkey="3"><input type="checkbox" tabindex="3" name=
        "ctl00$ContentPlaceHolder1$cbStudentTypeEdit$2" id=
        "ctl00_ContentPlaceHolder1_cbStudentTypeEdit_2" />
        <label for="ctl00_ContentPlaceHolder1_cbStudentTypeEdit_2">November</label></span></td>
      </tr>

      <tr>
        <td><span idkey="2"><input type="checkbox" tabindex="3" name=
        "ctl00$ContentPlaceHolder1$cbStudentTypeEdit$1" id=
        "ctl00_ContentPlaceHolder1_cbStudentTypeEdit_1" />
        <label for="ctl00_ContentPlaceHolder1_cbStudentTypeEdit_1">December</label></span></td>

        <td><span idkey="4"><input type="checkbox" tabindex="3" name=
        "ctl00$ContentPlaceHolder1$cbStudentTypeEdit$3" id=
        "ctl00_ContentPlaceHolder1_cbStudentTypeEdit_3" />
        <label for="ctl00_ContentPlaceHolder1_cbStudentTypeEdit_3">January</label></span></td>
      </tr>
    </tbody>
  </table>

谢谢。

1 个答案:

答案 0 :(得分:2)

// jQuery wrapper
(function($){

    // document-ready wrapper
    $(function(){

        var arrMonth = [ "November", "October", "December"];

        //Loop through the array and check each element against the check box list
        //if found, make the checkbox checked
        $.each(arrMonth, function( intIndex, objValue) {

            $("label:contains('" + objValue + "')").each(function(){
                // jquery 1.5 and earlier: use attr instead of prop
                $("#" + $(this).attr("for")).prop("checked", true);
            });
        });

    });

})(jQuery);

工作演示:http://jsfiddle.net/roberkules/3QjYk/