简体   繁体   中英

How to get data attribute value for selected option?

When I selected he just get value name Ahmad - how can I get the value ahmad zakaria ?

HTML:

<select name="kd_produk" id="family">
    <option value="one"
    data-name= "Ahmad Zakaria"
    data-wife= "My wife">number one</option>
</select>

JS

$("select#family").change(function(){
var name1 = $('select#family').find(':selected').data('name1');
var wife1 = $('select#family').find(':selected').data('wife1');

There is no attribute wife1 or name1 in your markup for the select element's <option /> .

Try removing 1 from each key string that you're passing to the .data() method:

var name = $('select#family').find(':selected').data('name');
var wife = $('select#family').find(':selected').data('wife');

This will ensure the values corresponding to the attrbiutes data-wife and data-name are retrieved as expected:

 var name = $('select#family').find(':selected').data('name'); var wife = $('select#family').find(':selected').data('wife'); console.log('data-name of selected:', name) console.log('data-wife of selected:', wife) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <select name="kd_produk" id="family"> <option value="one" data-name= "Ahmad Zakaria" data-wife= "My wife">number one</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM