Uzair Khan
Uzair Khan

Reputation: 2970

Get all input boxes and take their attribute values

I have a list of checkboxes which when checked I should get them and should retrieve their attribute values.

res.querySelectorAll('.node:checked')

Which gives me an array of checked input elements, I can use for loop to iterate through this array of elements and do

getAttribute('data-keyvalue') 

on each. But is it possible to get them in one line only, something in

querySelectorAll

Upvotes: 0

Views: 371

Answers (3)

Hassan Imam
Hassan Imam

Reputation: 22534

You can use Array#from to convert output which is NodeList of querySelectorAll into array and then use array#map to get the data-keyvalue attribute of the checked checkbox.

var checkboxAttributes = Array.from(document
  .querySelectorAll('.node:checked'))
  .map(input => input.getAttribute('data-keyvalue'));
console.log(checkboxAttributes);
<input class="node" data-keyvalue="7" type="checkbox" checked>
<input class="node" data-keyvalue="8" type="checkbox">
<input class="node" data-keyvalue="9" type="checkbox" checked>
<input class="node" data-keyvalue="10" type="checkbox" checked>
<input class="node" data-keyvalue="11" type="checkbox">

Upvotes: 3

kapantzak
kapantzak

Reputation: 11750

Check the console, it will log an array of checked data attributes values.

var chk = Array.prototype.slice.call(document.querySelectorAll('.node:checked')).map(function(node) {
  return node.getAttribute('data-keyvalue');
})
console.log(chk);
<input type="checkbox" class="node" checked data-keyvalue="1" />
<input type="checkbox" class="node" checked data-keyvalue="2" />
<input type="checkbox" class="node" checked data-keyvalue="3" />
<input type="checkbox" class="node" data-keyvalue="4" />
<input type="checkbox" class="node" data-keyvalue="5" />
<input type="checkbox" class="node" checked data-keyvalue="6" />
<input type="checkbox" class="node" checked data-keyvalue="7" />

Upvotes: 1

Clayton Bez
Clayton Bez

Reputation: 114

I came across the same issue, in the end all my searching amounted to, you have to process them one at a time and build either an array or string yourself. Try creating a function that does this for you and whenever you need to get them all, the function will give you data in the format you need.

Upvotes: 0

Related Questions