Foreach select attr value

I am capturing all values inside the name[] I can able to get the input value by the below code but I don’t know How I capture the input attr value by using this method below, please help

HTML

<input name="name[]" type="checkbox" my-at="123">
<input name="name[]" type="checkbox" my-at="456">

JavaScript (jQuery)

 var selectvalue= [];
$('input[name="name[]"]').each(function() {
   selectvalue.push(this).attr('my-at');
});

You should not create own attribute names like this. For this datasets are created

but still not get the value of attr

Could you not do something like this:

<fieldset>
  <legend>Choose your interests</legend>
  <div>
    <input type="checkbox" id="coding" name="interest" value="coding" />
    <label for="coding">Coding</label>
  </div>
  <div>
    <input type="checkbox" id="music" name="interest" value="music" />
    <label for="music">Music</label>
  </div>
</fieldset>

And:

const inputs = document.querySelectorAll('input[name="interest"]');
const selectValue = [...inputs].map((el) => el.value);
console.log(selectValue);
// ['coding', 'music']

can I write this in jQuery like below

 var selectvalue= [];
$('input[name="interest[]"]').each(function() {
   selectvalue.push(this).attr('value');
});

What does your markup now look like? That won’t work with what you posted previously in the thread, nor with the code I posted.

But in principle, yeah, why not?

In jQuery that would just be .val(), but you’ve also got the previous ) in the wrong place. Push the value, not just this.

Also, you’re capturing all the values, not just the checkboxes that have been checked.

Using .map:

let selected = $("input[name='name[]']:checked").map(function() { return $(this).val(); }).get();

Using .each and .push:

 let selectvalue = [];
 $('input[name="name[]"]:checked').each(function() { selectvalue.push($(this).val()); });
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.