I have this function, where I am currently pre-selecting all checkboxes:
function setupModuleSelection(selectedModules, preSelected) {
// TODO: preSelected not used
$('#my-table > tbody > tr > td.module_id > input[type="checkbox"]')
.prop('checked', true);
}
Where preSelected = ['module-001', 'module-003', 'module-027']
(for example):
The table is:
<tr>
...
<td class="module_id"><input type="checkbox" name="module_id" value="module-027"></td>
</tr>
Now I want to activate the checkboxes by filtering on the module_id
, as provided by the preSelected
array. How can I do this with jQuery?
Use attribute-value selector as follow
var preSelected = ['module-001', 'module-003', 'module-027'];
var selector = ':checkbox[value="' + preSelected.join('"], :checkbox[value="') + '"]';
$(selector).prop('checked', true);
The value of selector
will be
:checkbox[value="module-001"], :checkbox[value="module-003"], :checkbox[value="module-027"]
And passing this string to the jQuery object will select all the required checkboxes.
Live Demo:
var vowels = ['a', 'e', 'i', 'o', 'u']; var selector = ':checkbox[value="' + vowels.join('"], :checkbox[value="') + '"]'; console.log(selector); $(selector).prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="checkbox" name="aa" value="a" /> A <input type="checkbox" name="bb" value="b" /> B <input type="checkbox" name="Cc" value="c" /> C <input type="checkbox" name="dd" value="d" /> D <input type="checkbox" name="ee" value="e" /> E <input type="checkbox" name="ff" value="f" /> F <input type="checkbox" name="ii" value="i" /> I
preSelected = ['module-001', 'module-003', 'module-027'];
[].forEach.call(preSelected, function(val){
$("#my-table input[type='checkbox'][value='"+val+"']").prop('checked', true);
});
You can use something like this, selecting the input
based on the value.
您可以联接数组值以生成等于属性的选择器:
$('#my-table > tbody > tr > td.module_id > input[type="checkbox"][value="' + preSelected .join('"],[value="') + '"]').prop('checked', true);
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.