I have this code html:
我有这个代码html:
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
How can I take the value of the name attribute with jQuery? I tried the following code but did not return anything:
如何使用jQuery获取name属性的值?我尝试了以下代码,但没有返回任何内容:
val_id_template = $('#id_select').append().attr("name");
console.log(val_id_template);
Thank you!
谢谢!
1 个解决方案
#1
4
Remove append()
and try. It will give you the name
value of the selected option
in the select
list when you use $('#id_select option:selected')
:
删除append()并尝试。当您使用$('#id_select option:selected')时,它将为您提供选择列表中所选选项的名称值:
val_id_template = $('#id_select option:selected').attr("name");
console.log(val_id_template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
Or if you want to get the value of name
on selecting the option
from the list then:
或者,如果要从列表中选择选项时获取name的值,则:
$('#id_select').change(function(){
console.log($('#id_select option:selected').attr('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
#1
4
Remove append()
and try. It will give you the name
value of the selected option
in the select
list when you use $('#id_select option:selected')
:
删除append()并尝试。当您使用$('#id_select option:selected')时,它将为您提供选择列表中所选选项的名称值:
val_id_template = $('#id_select option:selected').attr("name");
console.log(val_id_template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>
Or if you want to get the value of name
on selecting the option
from the list then:
或者,如果要从列表中选择选项时获取name的值,则:
$('#id_select').change(function(){
console.log($('#id_select option:selected').attr('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='id_select'>
<option name='nm_opt' value='23'>Val1</option>
<option name='nm_opt2' value='16'>Val2</option>
<option name='nm_opt' value='6'>Val3</option>
</select>