Home  >  Article  >  Web Front-end  >  How to set select value in javascript

How to set select value in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-12 17:04:2211596browse

How to set the select value in javascript: 1. Set the select value in native js, the code is [var gd2=document.getElementById("goods_name2")]; 2. Set the select value in jquery.

How to set select value in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

How to set the select value in javascript:

1. How to set the select value in native js

(1) Sometimes You may need to hide the select, but you also need to change the value passed by the select. (The default selected value of select is the first one, that is, the option value with subscript 0)

var gd2=document.getElementById("goods_name2");
//为防止有时指定id元素不存在导致的异常
if(gd2)
{
 gd2[0].value=newvalue;
}

(2) Native js changes the selected value of select

var gd2=document.getElementById("goods_name2");
//为防止有时指定id元素不存在导致的异常
if(gd2)
{ 
   gd2.value=newvalue; //更改选定项,值为select选项中原有值(即换一个选择项)
}
var obj = document.getElementById("goods_name"); //定位id
var index = obj.selectedIndex; // 选中索引
obj.options[index].value=newvalue;//更改选定项的原有值(产生了新的选择项)

2, How to set select value in jquery

//设置select选定的值
$('#goods_name2 option:selected') .val(newvalue);

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to set select value in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more