I am using the on() method in jquery and I want to know if it's possible to shorten my code because I am just using the code over and over again but with different child selectors. Is it possible to use multiple child selectors in one on()?
This is a sample code and I have a lot of code like this.
$(document.body).on('change', 'input[name*="create"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
$(document.body).on('change', 'input[name*="compute"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
$(document.body).on('change', 'input[name*="print"]', function() {
var $class = $(this).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
});
I want to know if it's possible to use multiple 'input[name*="create"]' in one on() so that I won't have to repeat it.
Use Multiple Selector (“selector1, selector2, selectorN”)
$(document.body).on('change', 'input[name*="create"],input[name*="print"], input[name*="compute"]', function () {
...
});
If you are going to use the same function lines in multiple places, declare it to a single function name at first. Then you can call it whenever you need it.
For the implementing part, you can implement one event to multiple classes with css selector. (below)
function dotheAction(e) {
var $class = $(e).attr('class');
if (!$(this).is(':checked')) { //not checked
$('input[name*="' + $class + '_selectall"]').attr({
'checked': false
});
} else {
$('input[name*="' + $class + '_selectall"]').attr({
'checked': true
});
}
};
$(document.body).on('change', 'input[name*="create"], input[name*="compute"], input[name*="print"]', dotheAction(this));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Never target-reference other elements by using the caller's className. One day you'll add a styling class to your element and your JS will break and let you wondering.
Instead Use data-* attribute to reference:
<input type="checkbox" data-target="create"> Create<br>
<input type="checkbox" data-target="compute"> Compute <br>
<input type="checkbox" data-target="print"> Print<br>
considering that the i.e: create above will target all
<input type="checkbox" name="create_selectall">
elements, than this is all you need.
Really.
$("body").on('change', 'input[data-target]', function() {
$('input[name*="'+ this.dataset.target +'_selectall"]').prop({checked: !this.checked});
});