如何获取所选选项的数据属性值?

时间:2018-11-09 02:36:38

标签: javascript html

当我选择他时,他只是得到值名称Ahmad-如何获得值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');

1 个答案:

答案 0 :(得分:0)

标记中没有选择元素wife1的属性name1<option />

尝试从传递给1方法的每个键字符串中删除.data()

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

这将确保按预期方式检索与属性data-wifedata-name对应的值:

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>