改变选择值点击与javascript

Change select value on click with javascript

本文关键字:javascript 选择 改变      更新时间:2023-09-26

为这么基本的问题道歉,但我在任何地方都找不到答案。当单击按钮时,我需要更改一个选择传递到下一页的值。我不是想改变本页的选项列表,而是想改变选择传递到下一页的值。

<form name="myform" action="test2.php" method="get">
<select name="selectname" id="selectid">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <input type="submit" onclick="document.getElementById('selectid').value='3';" />
</form>

如果它是一个输入而不是一个选择,我可以很容易地改变传递的值,但由于某种原因,我无法让它与选择一起工作。直接的javascript或原型答案都可以。

没有值为3的选项,因此document.getElementById('selectid').value='3';将不起作用。

设置<select>方式的值只是选择具有匹配值的选项。如果这个值不存在,什么也不会发生。这就是你想要做的吗?


编辑

如果@JohnP在他的评论中建议的是你想要实现的,即改变value属性为<option>,你可以在点击时调用的函数中做到这一点:

var s = document.getElementById('test'); //get the select element
var o = s.options[s.selectedIndex]; //get the option element that is selected
o.value='3'; //change it's value
//o.innerHTML = '3'; //optionally change the text displayed