Javascript Fuction Calling Dynamically Classname
my goal is that when the user clicks the checkbox, it will count how many checked inputs there is with the same class name. I'm trying to send the var e into the counting function
Solution 1:
Remove onclick="b(this.className)"
. Define countChecked
at global level. Set click event with $("input[type=checkbox]").on("click", countChecked);
. Then you can use this.className
inside countChecked
. It will work fine.
View
<br><label><inputclass="tuesdayMorBar"type="checkbox"name="worker_name[]"value="<?phpecho$shift['fullname'];?>" />
Javascript
var countChecked = function() {
var n = $('.' + this.className + ':checked').length;
alert(n + (n === 1 ? " is" : " are") + " checked!");
};
$("input[type=checkbox]").on("click", countChecked);
Solution 2:
You can query for selectors with specific classes and attributes using querySelectorAll.
Try with this:
functionb() {
var checkedInputs = document.querySelectorAll("input.your-class-name[type='checkbox']:checked");
alert((checkedInputs.length === 1 ? "is" : "are") + " checked!");
}
Solution 3:
I have made a working snippet for your problem @Victoria's Secret. Comments are mentioned in the snippet itself. See if this resolves your issue.
functionb(e) {
let totalChecked = 0; // initialize the variable with 0;
$("input[type=checkbox]." + e).each(function() { // check every checkbox with class e(e has className)//console.log($(this));if ($(this).is(":checked")) { // check if checkboxed is checked
totalChecked++; // increment every time
}
});
alert(`class ${e}: ${totalChecked}`);
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><br><label><inputonchange="b(this.className)"class="kaka"type="checkbox"name="worker_name[]"value="kaka1" />kaka1
<inputonchange="b(this.className)"class="kaka"type="checkbox"name="worker_name[]"value="kaka2" />kaka2
<inputonchange="b(this.className)"class="kaka"type="checkbox"name="worker_name[]"value="kaka3" />kaka3
<br><br><inputonchange="b(this.className)"class="lala"type="checkbox"name="worker_name[]"value="lala1" />lala1
<inputonchange="b(this.className)"class="lala"type="checkbox"name="worker_name[]"value="lala2" />lala2
<br><br><inputonchange="b(this.className)"class="jaja"type="checkbox"name="worker_name[]"value="jaja1" />jaja1
<inputonchange="b(this.className)"class="jaja"type="checkbox"name="worker_name[]"value="jaja2" />jaja2
Post a Comment for "Javascript Fuction Calling Dynamically Classname"