gpt4 book ai didi

javascript - 如何从选项值转到 "link"按钮?

转载 作者:可可西里 更新时间:2023-11-01 13:01:06 26 4
gpt4 key购买 nike

更改选项值后如何转到“链接”按钮并单击提交?我遇到了问题,因为当我更改值时,它会在我单击提交之前“链接”

<form action="search-form" method="post">
<select onChange="window.location.href=this.value" >
<option value="here comes a link nr 1">coffie medium</option>
<option value="here comes a link nr 2">coffe big</option>
</select>
<button type="submit" name="submit" value="submit"><img src="xyz.JPG" width="240" height="72">
</button>
</form>

最佳答案

select 元素中删除 onchange 并为您的提交按钮编写一个监听器(您已经在使用 search-form 操作)

<form action="search-form" method="post">
<select>
<option value="here comes a link nr 1">coffie medium</option>
<option value="here comes a link nr 2">coffe big</option>
</select>
<button type="submit" name="submit" value="submit"><img src="xyz.JPG" width="240" height="72">
</button>
</form>

编辑:@Peril 根据要求添加解决方案。现在,如果您使用 onsubmit 进行表单提交,它就可以正常工作了,如下所示。请注意,您应该为 option 值提供有效链接

function submit_form() {
window.location.href= document.getElementById('select-box').value;
}
<form onsubmit="submit_form()" method="post">
<select id="select-box">
<option value="http://google.com">coffie medium</option>
<option value="http://yahoo.com">coffe big</option>
</select>
<button type="submit" name="submit" value="submit">submit</button>
</form>

编辑 2:@Peril 通常我们在点击 anchor 标签时将外部链接加载到页面中。如果您使用 window.location.href 加载它,您将收到 cross-origin access 错误。将以下代码片段放入本地 html 文件并检查。

// load href initially
document.getElementById('form-button').setAttribute('action', document.getElementById('select-box').value);
// load href on value change of select
function onChangeValue() {
document.getElementById('form-button').setAttribute('action', document.getElementById('select-box').value);
return false;
}
<body>
<select id="select-box" onchange="onChangeValue()">
<option value="http://www.google.com">coffie medium</option>
<option value="http://www.facebook.com">coffe big</option>
</select>
<form action="#" id="form-button" style="display:inline">
<input type="submit" value="Submit" />
</form>
</body>

关于javascript - 如何从选项值转到 "link"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com