关于html:如何使用JavaScript以编程方式设置选择框元素的值?

关于html:如何使用JavaScript以编程方式设置选择框元素的值?

How do I programmatically set the value of a select box element using JavaScript?

我有以下HTML

1
2
3
4
5
6
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

使用以leaveCode数字作为参数的JavaScript函数,如何在列表中选择适当的选项?


您可以使用此功能:

1
2
3
4
5
6
selectElement('leaveCode', '11')

function selectElement(id, valueToSelect) {    
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

如果您使用的是jQuery,则还可以执行以下操作:

1
$('#leaveCode').val('14');

这将选择值为14的

使用纯Javascript,这也可以通过两个Document方法实现:

  • 使用document.querySelector,您可以基于CSS选择器选择一个元素:

    1
    document.querySelector('#leaveCode').value = '14'
  • 就像函数名称所暗示的那样,将更成熟的方法与document.getElementById()一起使用,可以让您根据其id选择一个元素:

    1
    document.getElementById('leaveCode').value = '14'

您可以运行下面的代码片段以查看这些方法和实际使用的jQuery函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const jQueryFunction = () => {
 
  $('#leaveCode').val('14');
 
}

const querySelectorFunction = () => {
 
  document.querySelector('#leaveCode').value = '14'
 
}

const getElementByIdFunction = () => {
 
  document.getElementById('leaveCode').value='14'
 
}
1
2
3
4
5
input {
  display:block;
  margin: 10px;
  padding: 10px
}
1
2
3
4
5
6
7
8
9
10
11
12
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">


1
2
3
4
function setSelectValue (id, val) {
    document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);

不回答问题,但是您也可以按索引选择,其中i是您要选择的项目的索引:

1
2
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;

您还可以循环浏览项目以按显示值选择:

1
2
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
    if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;

我比较了不同的方法:

比较如何使用JS或jQuery设置select值的方法

码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$(function() {
    var oldT = new Date().getTime();
     var element = document.getElementById('myId');
    element.value = 4;
    console.error(new Date().getTime() - oldT);


    oldT = new Date().getTime();
    $("#myId option").filter(function() {
        return $(this).attr('value') == 4;
    }).attr('selected', true);
    console.error(new Date().getTime() - oldT);


    oldT = new Date().getTime();
    $("#myId").val("4");
    console.error(new Date().getTime() - oldT);


});

在具有?4000个元素的选择中输出:

1毫秒

58毫秒

612毫秒

使用Firefox10。注意:我进行此测试的唯一原因是,由于jQuery在我们的列表上的表现非常差,有大约2000个条目(它们之间的选项之间的文本较长)。
val()之后大约有2秒的延迟

还要注意:我根据实际值而不是文本值来设置值


1
document.getElementById('leaveCode').value = '10';

那应该将选择设置为"年假"


我尝试了上述基于JavaScript / jQuery的解决方案,例如:

1
$("#leaveCode").val("14");

1
2
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;

在AngularJS应用中,其中有必需的

1
$("#leaveCode").val("14").change();

1
2
3
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();

如果需要,最简单的方法是:
1)单击定义选择选项的按钮
2)转到另一页,其中选择选项为
3)在另一页上选择该选项值

1)您的按钮链接(例如,在主页上)

1
2
Sales
IT

(其中contact.php是您的带有选择选项的页面。请注意,页面网址具有?option = 1或2)

2)将此代码放在第二页上(我的案例contact.php)

1
2
3
4
<?
if (isset($_GET['option']) && $_GET['option'] !="") {
$pg = $_GET['option'];              
} ?>

3)根据单击的按钮,选择选项值

1
2
3
4
<select>
<option value="Sales" <? if ($pg == '1') { echo"selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo"selected"; } ?> >IT</option>
</select>

.. 等等。
因此,这是通过url中的GET将值传递到另一个页面(带有选择选项列表)的简单方法。没有表格,没有ID ..仅需3个步骤,就可以完美地工作。


1
2
3
4
5
6
7
<wyn>
function foo(value)
{
    var e = document.getElementById('leaveCode');
    if(e) e.value = value;
}
</wyn>

假设您的表单名为form1:

1
2
3
4
5
6
7
8
9
10
11
12
function selectValue(val)
{
  var lc = document.form1.leaveCode;
  for (i=0; i<lc.length; i++)
  {
    if (lc.options[i].value == val)
    {
        lc.selectedIndex = i;
        return;
    }
  }
}

为什么不为元素的ID添加变量并使它成为可重用的函数?

1
2
3
4
5
function SelectElement(selectElementId, valueToSelect)
{    
    var element = document.getElementById(selectElementId);
    element.value = valueToSelect;
}


应该遵循以下原则:

1
2
3
4
5
6
7
8
9
10
11
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
  if (dl.options[i].value == inVal){
    el=i;
    break;
  }
}
dl.selectedIndex = el;
}

您最可能希望这样做:

1
$("._statusDDL").val('2');

要么

1
$('select').prop('selectedIndex', 3);

如果使用PHP,则可以尝试以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';

switch($value) {
            case '10' :
                $first = 'selected';
            break;
            case '11' :
                $second = 'selected';
            break;
            case '14' :
                $third = 'selected';
            break;
            case '17' :
                $fourth = 'selected';
            break;
        }

echo'
<select id="leaveCode" name="leaveCode">
  <option value="10" '
. $first .'>Annual Leave</option>
  <option value="11" '
. $second .'>Medical Leave</option>
  <option value="14" '
. $third .'>Long Service</option>
  <option value="17" '
. $fourth .'>Leave Without Pay</option>
</select>'
;

恐怕目前无法测试,但是在过去,我相信我必须给每个选项标签指定一个ID,然后执行以下操作:

1
document.getElementById("optionID").select();

如果那不起作用,也许它将使您更接近解决方案:P


推荐阅读

    linux设置命令行长度?

    linux设置命令行长度?,系统,工作,信息,地址,命令,工具,异常,管理,目录,文件,l

    linux设置代替命令?

    linux设置代替命令?,系统,地址,网络,工作,软件,工具,服务,信息,命令,别名,lin

    linux命令设置时区?

    linux命令设置时区?,时间,系统,国家,大陆,命令,时区,时钟,日期,指令,时分,lin

    linux控制台编程命令?

    linux控制台编程命令?,系统,工具,环境,命令,名称,标准,不了,工作,发行,基础,s

    linux编程常用命令?

    linux编程常用命令?,系统,工作,信息,命令,地址,管理,工具,网络,基础,目录,lin

    linux设置命令限制?

    linux设置命令限制?,数字,情况,信息,管理,系统,最新,在线,设备,第一,发行,Lin

    linux设置日志命令行?

    linux设置日志命令行?,异常,系统,实时,日志,管理,信息,对比,项目,名称,情况,L

    linux命令行设置网卡?

    linux命令行设置网卡?,系统,地址,信息,网络,工具,电脑,工作,名称,设备,网卡,l

    linux命令优先级设置?

    linux命令优先级设置?,系统,时间,实时,策略,优先级,分时,管理,周期性,进程,

    linux设置ip命令?

    linux设置ip命令?,地址,系统,密码,设备,命令,服务,工具,网络,网卡,计算机,在L

    linux设置命令是什么?

    linux设置命令是什么?,系统,工作,信息,名称,地址,命令,在线,基础,标准,工具,l

    linux命令设置密码?

    linux命令设置密码?,密码,系统,服务,软件,地址,电脑,流程,管理,用户,命令,问

    linux设置编码命令?

    linux设置编码命令?,系统,数据,发展,文件,字符集,命令,数据库,以下,终端,大

    linux命令行设置语言?

    linux命令行设置语言?,系统,管理,环境,国家,工具,电脑,软件,文化,底部,语言,l

    linux设置壁纸的命令?

    linux设置壁纸的命令?,图片,系统,电脑,照片,位置,终端,颜色,字体,单击,壁纸,

    linux恢复命令行设置?

    linux恢复命令行设置?,系统,工作,密码,信息,工具,地址,电脑,命令,情况,地方,

    linux命令提示设置?

    linux命令提示设置?,系统,工作,地址,信息,命令,软件,目录,管理,变量,文件,Lin

    linux设置命令ip?

    linux设置命令ip?,地址,系统,代码,命令,密码,网卡,终端,计算机,测试,网关,lin

    linux设置man命令?

    linux设置man命令?,信息,系统,工具,工作,地址,命令,基础,地方,基本知识,技术

    linux鼠标设置命令?

    linux鼠标设置命令?,系统,软件,环境,产品,设备,数据,网络,网址,工具,情况,lin