简体   繁体   中英

Check all checboxes if they have the same value

this is my html code:

 <ul>
   <li>
  <input name="Services[]" class="form-control" value="Canbeprivatized" id="Canbeprivatized" type="checkbox"><label for="Canbeprivatized">Can be privatized </label>
   </li>
   <li>
   <input name="Services[]" class="form-control" value="Englishspoken" id="Englishspoken" type="checkbox"><label for="Englishspoken">English spoken </label>
   </li>
   <li>
   <input name="Services[]" class="form-control" value="Françaisparle" id="Françaisparle" type="checkbox"><label for="Françaisparle">Français parlé </label>
   </li>
   <li>
   <input name="Services[]" class="form-control" value="Petsallowed" id="Petsallowed" type="checkbox"><label for="Petsallowed">Pets allowed </label>
   </li>
   <li>
   <input name="Services[]" class="form-control" value="Piscine" id="Piscine" type="checkbox"><label for="Piscine">Piscine </label>
   </li></ul>

jQuery code:

var tab = new Array();
tab = data.services.split(",");// data is values of Checkboxes inserted in create form, so now i need to show it because this is edit form

My question is how to check all checkboxes who have values equal to values in tab. Need your help and thank's

Do as follows, iterating on tab :

for (i = 0; i < tab.length; i++)
  $('input[type=checkbox][value=' + tab[i] + ']').prop("checked", true);

You can use .filter() to find all checkboxes whose value exists in array tab then use .prop() to set its checked property

$(':checkbox').filter(function(){
    return tab.indexOf($(this).val()) > -1;
}).prop('checked', true);

If I understood correctly this should work

var tab = 'Englishspoken,Petsallowed';
tab = tab.split(",");
var $input = $('input');
for (var i = 0; i < $input.length; i++){
    for (var j = 0; j < tab.length; j++){
        if ($input.eq(i).val() == tab[j]){
            $input.eq(i).prop('checked', true);
        }
    }
}

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM