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

How to set select value in javascript

coldplay.xixi
Release: 2023-01-05 16:07:40
Original
11650 people have browsed it

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;
}
Copy after login

(2) Native js changes the selected value of select

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

2, How to set select value in jquery

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template