I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
With jQuery, you can use the . val() method to get the value of the Value attribute of the desired input checkbox.
The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
Store all selected checkbox value in array using for loop. Inside this function, create a new blank array ( let arr = [] ). Then, store the selected checkbox into a variable using querySelectorAll() method. The querySelector() method returns the first element that matches the specified selectors.
To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' . Save this answer.
Instead return $(this).val();
you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With