使用 javascript 更改点击时的选择值

发布于 2024-11-04 23:37:08 字数 525 浏览 0 评论 0原文

对于这么基本的问题表示歉意,但我在任何地方都找不到答案。单击按钮时,我需要更改选择传递到下一页的值。我并不是试图更改此页面上的选项列表,而是尝试更改选择传递到下一页的值。

<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 或原型答案都可以。

Apologies for so basic a question, but I can't find an answer anywhere. When the button is clicked, I need to change the value a select passes to the next page. I'm not trying to change the option list on this page, but rather trying to change the value which the select passes to the next page.

<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>

I could easily change the passed value if it were an input rather than a select, but for some reason I am unable to get this to work with a select. Either a straight javascript or a prototype answer will work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好倦 2024-11-11 23:37:08

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

设置


编辑

如果@JohnP在他的评论中建议的是您想要实现的目标,即更改value属性,您可以在单击时调用的函数中执行此操作:

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

There is no option with the value 3 so document.getElementById('selectid').value='3'; will have no effect.

Setting the value for a <select> way simply selects the option with the matching value. If that value doesn't exist, nothing happens. Is that what you're trying to do?


Edit

If what @JohnP suggested in his comment is what you're trying to achieve i.e. change the value attribute for an <option>, you could do this in a function that is invoked on click:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文