Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data attribute from radio button with JavaScript?

I want to get the data-price value from radio button which is checked. I tried something like that:

<input type="radio" name="vehicletype" id="vehicletype" value="{{$vehicletypeData->id}}" data-price="{{$vehicletypeData->km_rate}}" required="">


var vehicleTyp=document.getElementById("vehicletype");
                var vetselindx=vehicleTyp.options[vehicleTyp.selectedIndex];
                var prikm=vetselindx.getAttribute("data-price");

But this does not work. How can I solve this issue?

like image 693
Karthik Avatar asked Nov 18 '25 11:11

Karthik


1 Answers

document.getElementById("vehicletype");

This gets the element with that id. The single element with that id. Multiple elements in a document cannot share an id.

vehicleTyp.options

Select elements have options. Radio buttons do not.


To find the checked element you should:

  • Get all the radio buttons. Consider getElementsByName
  • Loop over them until you find one where the checked property is true

Once you have found the element you are looking for you can use getAttribute("data-price"); or the dataset property.

like image 138
Quentin Avatar answered Nov 20 '25 02:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!