Narazana
Narazana

Reputation: 1950

Make checkbox checked by comparing the values

I have the following Checkbox list, which is generated from server in HTML format. I also have an Javascript array like the following. I want to loop through the the array and check each value against the each checkbox. If there's a match, then make that checkbox checked.

I'm using 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>

Generated Checkbox list:

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

Thank you.

Upvotes: 0

Views: 1878

Answers (1)

roberkules
roberkules

Reputation: 6605

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

Working demo: http://jsfiddle.net/roberkules/3QjYk/

Upvotes: 2

Related Questions