如何使用JQuery,Javascript和html动态设置下拉列表的选定选项?

时间:2021-10-24 07:34:14

For some reason, I can't get this to work.

出于某种原因,我不能让这个工作。

My options list is populated dynamically using these scripts:

我的选项列表使用以下脚本动态填充:

function addOption(selectId, value, text, selected) {
    var html = '<option value="'+value+'">'+text+'</option>';
    if (selected == "on") {
        html = '<option value="'+value+'" selected="selected">'+text+'</option>';
    }
    $('#'+selectId).append(html);
}

function addSalespersonOption(id, name, defsales) {
    addOption('salesperson', id, name, defsales);
}

Here is the html:

这是html:

td class="text-r"><label for="salesperson">Salesperson:</label></td>
<td>
    <select id="salesperson">
        <option value="">(select)</option>
    </select>
</td>

So far, the output is:

到目前为止,输出是:

<option value="1266852143634" selected="selected">Eric Hunt</option>

The DOM shows this:

DOM显示了这个:

index              2
disabled           false
value              "1266852143634"
text               "Eric Hunt"
selected           false
defaultSelected    true

But for some reason, when the page is loaded, the dropdown does not display Eric Hunt as pre selected. Nor is anything for that matter.

但由于某种原因,当页面加载时,下拉列表不会显示Eric Hunt为预选。这件事也没有。

how can I get "selected true" instead of "defaultSelected true".

我如何得到“选择真”而不是“defaultSelected true”。


EDIT: As it turns out, the above code works perfectly, thanks to the help of deceze and rosscj2533's answers from below. The only reason it's not working for me is, I found ruby code that was overwriting the select elements.

编辑:事实证明,上面的代码完美地工作,感谢deceze的帮助和rosscj2533从下面的答案。它不适合我的唯一原因是,我发现ruby代码覆盖了select元素。

Thanks for everyone's help on this,

感谢大家的帮助,

Cheers

干杯

7 个解决方案

#1


17  

The defaultSelected attribute is not settable, it's just for informational purposes:

defaultSelected属性不可设置,仅供参考:

Quote:

引用:

The defaultSelected property returns the default value of the selected attribute.
This property returns true if an option is selected by default, otherwise it returns false.

defaultSelected属性返回所选属性的默认值。如果默认选择了一个选项,则此属性返回true,否则返回false。

I think you want:

我想你想要:

$('option[value=valueToSelect]', newOption).attr('selected', 'selected');

I.e. set the selected attribute of the option you want to select.

即设置要选择的选项的选定属性。


Without trying to fix your code, here's roughly how I would do it:

在不尝试修复代码的情况下,我大致会这样做:

function buildSelect(options, default) {
    // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
    //        default = 'value1'

    var $select = $('<select></select>');
    var $option;

    for (var val in options) {
        $option = $('<option value="' + val + '">' + options[val] + '</option>');
        if (val == default) {
            $option.attr('selected', 'selected');
        }
        $select.append($option);
    }

    return $select;
}

You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

你似乎已经有很多行李和依赖,我无法告诉你如何最好地将选定的选项集成到你的代码中而不会看到更多,但希望这会有所帮助。

#2


2  

Here is another way you can change the selected option of a <select> element in javascript. You can use

这是另一种可以在javascript中更改

document.getElementById('salesperson').selectedIndex=1;

的document.getElementById( '销售员')的selectedIndex = 1。

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

将其设置为1将使下拉列表的第二个元素被选中。 select元素索引从0开始。

Here is a sample code. Check if you can use this type of approach:

这是一个示例代码。检查您是否可以使用此类方法:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

#3


1  

Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?

请原谅我的无知,但为什么在处理身份证时你使用$('。salesperson')而不是$('#salesperson')?

#4


1  

Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

你的代码适合我。什么时候调用addSalespersonOption?该呼叫可能存在问题。

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

还有一些你的html有点关闭(可能是复制/粘贴问题?),但这似乎没有引起任何问题。您的选择应如下所示:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

而不是这个:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

编辑:您的选项列表何时动态填充?您确定在调用addSalespersonOption时为defSales值传递'on'吗?尝试将该代码更改为:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

并查看警报是否发生以及如果确实发生了什么。

Edit: Working example of my testing (the error:undefined is from jsbin, not my code).

编辑:我的测试的工作示例(错误:undefined来自jsbin,而不是我的代码)。

#5


1  

SCRIPT

脚本

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details

点击这里更多详情

#6


0  

Your syntax is wrong.

你的语法错了。

You need to call attr with two parameters, like this:

您需要使用两个参数调用attr,如下所示:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected" to the variable defaultSelected, then passes that value to the attr function, which will then return the value of the selected attribute.

您当前的代码将值“selected”分配给变量defaultSelected,然后将该值传递给attr函数,然后attr函数将返回所选属性的值。

#7


0  

Here it goes.

在这里。

// Select by value
$('select[name="options"]').find('option[value="3"]').attr("selected",true);

// Select by text
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<select name="options">
      <option value="1">First</option>
      <option value="2">Second</option>
      <option value="3">Third</option>
</select>
</body>
</html>

#1


17  

The defaultSelected attribute is not settable, it's just for informational purposes:

defaultSelected属性不可设置,仅供参考:

Quote:

引用:

The defaultSelected property returns the default value of the selected attribute.
This property returns true if an option is selected by default, otherwise it returns false.

defaultSelected属性返回所选属性的默认值。如果默认选择了一个选项,则此属性返回true,否则返回false。

I think you want:

我想你想要:

$('option[value=valueToSelect]', newOption).attr('selected', 'selected');

I.e. set the selected attribute of the option you want to select.

即设置要选择的选项的选定属性。


Without trying to fix your code, here's roughly how I would do it:

在不尝试修复代码的情况下,我大致会这样做:

function buildSelect(options, default) {
    // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
    //        default = 'value1'

    var $select = $('<select></select>');
    var $option;

    for (var val in options) {
        $option = $('<option value="' + val + '">' + options[val] + '</option>');
        if (val == default) {
            $option.attr('selected', 'selected');
        }
        $select.append($option);
    }

    return $select;
}

You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

你似乎已经有很多行李和依赖,我无法告诉你如何最好地将选定的选项集成到你的代码中而不会看到更多,但希望这会有所帮助。

#2


2  

Here is another way you can change the selected option of a <select> element in javascript. You can use

这是另一种可以在javascript中更改

document.getElementById('salesperson').selectedIndex=1;

的document.getElementById( '销售员')的selectedIndex = 1。

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

将其设置为1将使下拉列表的第二个元素被选中。 select元素索引从0开始。

Here is a sample code. Check if you can use this type of approach:

这是一个示例代码。检查您是否可以使用此类方法:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

#3


1  

Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?

请原谅我的无知,但为什么在处理身份证时你使用$('。salesperson')而不是$('#salesperson')?

#4


1  

Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

你的代码适合我。什么时候调用addSalespersonOption?该呼叫可能存在问题。

Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

还有一些你的html有点关闭(可能是复制/粘贴问题?),但这似乎没有引起任何问题。您的选择应如下所示:

<select id="salesperson"> 
    <option value="">(select)</option> 
</select>

instead of this:

而不是这个:

<select id="salesperson" /> 
    <option value"">(select)</option> 
</select>

Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

编辑:您的选项列表何时动态填充?您确定在调用addSalespersonOption时为defSales值传递'on'吗?尝试将该代码更改为:

if (selected == "on") { 
    alert('setting default selected option to ' + text);
    html = '<option value="'+value+'" selected="selected">'+text+'</option>'; 
} 

and see if the alert happens and what is says if it does happen.

并查看警报是否发生以及如果确实发生了什么。

Edit: Working example of my testing (the error:undefined is from jsbin, not my code).

编辑:我的测试的工作示例(错误:undefined来自jsbin,而不是我的代码)。

#5


1  

SCRIPT

脚本

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details

点击这里更多详情

#6


0  

Your syntax is wrong.

你的语法错了。

You need to call attr with two parameters, like this:

您需要使用两个参数调用attr,如下所示:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected" to the variable defaultSelected, then passes that value to the attr function, which will then return the value of the selected attribute.

您当前的代码将值“selected”分配给变量defaultSelected,然后将该值传递给attr函数,然后attr函数将返回所选属性的值。

#7


0  

Here it goes.

在这里。

// Select by value
$('select[name="options"]').find('option[value="3"]').attr("selected",true);

// Select by text
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<select name="options">
      <option value="1">First</option>
      <option value="2">Second</option>
      <option value="3">Third</option>
</select>
</body>
</html>