Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from data-attribute of selected dropdown

Tags:

I'm trying to select the data attribute from the selected option of a drop-down list then place it within a textbox. This is also my second data attribute. I'm going to add code for whenever the user changes the option (code I already have written and can abstract here), but I want to get this part to work first.

HTML

<select class="operations-supplier" name="operations-supplier">     <option data-selected="latam" data-capacity="100000" value="         10">LATAM - Supplier A</option>     <option data-selected="na" data-capacity="200000" value="20>">NA - Supplier B</option>     <option data-selected="asia" data-capacity="300000" value="30">ASIA - Supplier C</option> </select> <input type="text" class="operations-supplierCapacity" readonly /> 

JQuery

var capacityValue = $('select.operations-supplier').find(':selected').attr('data-capacity').val(); $('.operations-supplierCapacity').val(capacityValue); 

Jsfiddle

like image 283
dvoutt Avatar asked Jan 14 '14 04:01

dvoutt


People also ask

How to get data attribute value of selected option in JavaScript?

var attrs = option. attributes; Good. This is the alternative way for working with data attributes.

How do I select an element by a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.


1 Answers

You can use data() method in jQuery , Also add a change event for dropdown

$(document).ready(function() {     $('select.operations-supplier').change(function() {         var capacityValue = $('select.operations-supplier').find(':selected').data('capacity');         $('.operations-supplierCapacity').val(capacityValue);     }); }); 

FIDDLE

You need to wrap code within $(document).ready(function() {...}); , to bind event after dom element is loaded.

like image 76
Pranav C Balan Avatar answered Oct 23 '22 15:10

Pranav C Balan