Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Get data-attribute of all checkbox into a string

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?

like image 450
super-user Avatar asked Jul 25 '16 03:07

super-user


People also ask

How to get data value of a checkbox in jQuery?

With jQuery, you can use the . val() method to get the value of the Value attribute of the desired input checkbox.

How to get attr value jQuery?

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.

How do you store a selected checkbox value in an array?

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.

How to get attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' . Save this answer.


1 Answers

Instead return $(this).val(); you can use return $(this).data('id');

var receiptNos2 = $("#result input:checkbox:checked").map(function () {
    return $(this).data('id')
}).get();
like image 126
Dekel Avatar answered Sep 24 '22 20:09

Dekel