HTML / JS:如何使用JS更改选择类型的选项值 [英] HTML/JS: How to change option value of select type using JS

查看:83
本文介绍了HTML / JS:如何使用JS更改选择类型的选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚如何在选择类型中为一个选项设置一个值。但是,不管我多么努力去理解,我都不能(感到羞愧)。



所以我希望你们帮助我,因为你们帮助过我之前有这么多次:)



假设我们有:

 < select name =boxid =test> 
< option value ='tval'> Content< / option>

不应该在下一个代码中将文本从内容更改为框?

  function changeContent(form){
form.document.getElementById('test')。options ['tval']。value ='box';
}

还是我完全错了?我查了很多不同的文章,但没有人能帮助我理解如何做到这一点。



谢谢你们!



  > function changeContent(){
document.getElementById('test')。options [0] .text ='box';
}

设置值和文本;

  function changeContent(){
var opt = document.getElementById('test')。options [0];
opt.value ='box';
opt.text ='box';
}


I've been trying to figure out how to set a value to a an option in a select type. But no matter how much I try to understand I just can't (feels ashamed)..

So I was hoping that you guys could help me since you've helped me so many times before.. :)

Let's say we have:

<select name="box" id="test">    
<option value='tval'>Content</option>

shouldn't this next code change the text from 'Content' to 'box'?

function changeContent(form){
form.document.getElementById('test').options['tval'].value = 'box';
}

or am I completely wrong here? I've looked up so many different articles but no one could help me understand how to do this..

Thanks guys!

解决方案

If You need to change the text rather than the value;

function changeContent(){
     document.getElementById('test').options[0].text = 'box';
}

To set both the value and text;

function changeContent(){
     var opt= document.getElementById('test').options[0];
     opt.value =  'box';
     opt.text = 'box';
}

这篇关于HTML / JS:如何使用JS更改选择类型的选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆