Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data-value from radio input using jquery?

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?

like image 932
godot Avatar asked Dec 17 '22 23:12

godot


2 Answers

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>
like image 56
Scaramouche Avatar answered Jan 05 '23 11:01

Scaramouche


if you use newer jQuery >= 1.4.3 You can use like this.

$(this).data("value");

OR

$(this).data().value;
like image 23
Vikash sah Avatar answered Jan 05 '23 09:01

Vikash sah