Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String array to find and check checkboxes

I have a string split by commas. I use the javascript command split to break it into an array.

I have a group of checkboxes called ciContact.

<table border="0" cellspacing="0" cellpadding="6">
    <tr>
        <td><label>
            <input type="checkbox" name="ciContact[]" value="Call" id="ciContact_0" />
      Call</label></td>
    <td><label>
            <input type="checkbox" name="ciContact[]" value="Email" id="ciContact_1" />
      Email</label></td>

        <td><label>
            <input type="checkbox" name="ciContact[]" value="Text" id="ciContact_2" />
      Text</label></td>
    </tr>
</table>

The array contains just the values that need to be checked. These values are echoed back from an AJAX call that is JSON-encoded. However, these values (ciContact) are all stored in the MySQL database as a comma-delimited array. There is a reason I did it that way. So how do I read the values of my comma-delimited array and check the appropriate checkboxes?

I've tried:

var ciContact = data.split(", ");
for (var j = 0; j < ciContact.length; j++)
    {
var selected = $('name=ciContact').find('value='+ ciContact[i]);
selected.attr("checked","checked");
}

I'm way off on that one. Ha!

Thanks guys!

like image 288
swg1cor14 Avatar asked Sep 10 '26 18:09

swg1cor14


1 Answers

var ciContact = data.split(", ");
for (var j = 0; j < ciContact.length; j++) {
    $('input[name^=ciContact][value=' + ciContact[j] + ']').attr('checked','checked');`
}

Or, for slightly better performance:

var ciContact = data.split(", "),
    $inputs = $('input[name^=ciContact]');
for (var j = 0; j < ciContact.length; j++) {
    $inputs.filter('[value=' + ciContact[j] + ']').attr('checked','checked');`
}

Or, fancy:

var ciContact = data.split(", ").join('], [value='),
    $inputs = $('input[name^=ciContact]');

$inputs.filter('[value=' + ciContact + ']').attr('checked','checked');
like image 172
glortho Avatar answered Sep 13 '26 07:09

glortho