I have simple from which consists by inputs like that:
<form id='some-form'>
....
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
....
</form>
I'm trying to loop through this form and get data values:
$('#some-form').filter(':input').each(function (i, element) {
console.log(element.value);
console.log(element.attr('data-value'));
}
element.value
holds value 'on' or 'off' depending radio is chosen or not and it works properly but when I try to call element.attr('data-value')
it throws an error.
So how can I extract data-value in this loop?
use .children() instead of .filter().
The former will get you the elements inside the form, the latter will filter all elements $('#some-form')
will provide.
HIH
EDIT
as pointed out by gaetanoM and connexo, there is also the issue of using element.attr()
without the $()
which you will need since .attr()
is a method of jQuery, not JS
$('#some-form').children(':input').each(function (i, element) {
console.log(element.value);
console.log($(element).attr('data-value'));
//
// or
//
// console.log(element.dataset.value);
})
console.log('end');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
</form>
if you use newer jQuery >= 1.4.3 You can use like this.
$(this).data("value");
OR
$(this).data().value;
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