简体   繁体   English

如何使用jQuery设置选择框的第一个选项?

[英]How to set first option's of Select Box using jQuery?

I have a select list: 我有一个选择列表:

<select id='sf-field-1'> 
    <option></option> 
    <option value="1">one</option> 
    <option value="2">two</option> 
    <option value="3">three</option> 
</select>

How can I set the value of option value to the below by using jQuery? 如何使用jQuery将选项值设置为以下值?

<select id='sf-field-1'> 
    <option> -- Select -- </option> 
    <option value="1">one</option> 
    <option value="2">two</option> 
    <option value="3">three</option> 
</select>

I also tried jQuery("#sf-field-1 :first-child").attr("value", 0); 我还尝试了jQuery("#sf-field-1 :first-child").attr("value", 0); but this did not work for me. 但这对我没有用。 Any ideas? 有任何想法吗?

Your second attempt was close, you just need to set the text() of the element, not its value: 您的第二次尝试已结束,您只需要设置元素的text() ,而不是其值即可:

$("#sf-field-1 :first-child").text(" -- Select -- ");

Example fiddle 小提琴的例子

Another way to do this is using prepend function : What you do is that create dropdownlist with select options 另一种方法是使用prepend函数:您要做的是使用选择选项创建下拉列表

<select id='sf-field-1'> 
    <option value="1">one</option> 
    <option value="2">two</option> 
    <option value="3">three</option> 
</select>

and then using following jquery code add first option. 然后使用以下jquery代码添加第一个选项。

    var newOption = "<option selected='"+"selected"+"  '>--Select--</option>"; 
$("#sf-field-1").prepend(newOption);

基于编辑第一个选项名称可以使用

$('#sf-field-1 > option:empty:first').text(" -- Select -- ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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