我正在尝试在表单提交上设置条件页面加载,遵循“如果用户选择 [x] 选项,将它们发送到 [x] 页面”逻辑。我真的不太熟悉 JavaScript,但这似乎是最简单的方法。
这是我的 HTML:
<form id="page1" action="javascript:OpenWindow()" method="post">
<fieldset id="mainSelection">
<label><input type="radio" class="radio-button" value="A" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="B" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="C" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="D" name="sel1"> text</label><br />
</fieldset>
<button type="submit" value="Next" id="submitButton">Next</button>
</form>
这是我的脚本:
<script type="text/javascript" language="javascript">
function OpenWindow() {
var choice = document.getElementByClassName("radio-button").value
if (choice == A) {
window.open('http://www.website.net');
}
else if (choice == B) {
window.open('http://www.website.net');
}
else if (choice == C) {
window.open('http://www.website.net');
}
else {
window.open('http://www.website.net');
}
}
</script>
我在这里做错了什么?
最佳答案
我做了一些改动就可以使用它。
在表单元素中添加onsubmit="OpenWindow()"
更改获取所选元素的方式
围绕您的条件引用('A'、'B' 等)
这是代码笔的链接:http://codepen.io/anon/pen/qajxh
所以看起来像这样:
<form onsubmit="OpenWindow()" id="page1" action="javascript:OpenWindow()" method="post">
<fieldset id="mainSelection">
<label><input type="radio" class="radio-button" value="A" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="B" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="C" name="sel1"> text</label><br />
<label><input type="radio" class="radio-button" value="D" name="sel1"> text</label><br />
</fieldset>
<button type="submit" value="Next" id="submitButton">Next</button>
</form>
像这样的js:
function OpenWindow() {
var choice = document.getElementById("page1");
choice = choice.sel1.value;
if (choice == 'A') {
window.open('http://www.website.net');
}
else if (choice == 'B') {
window.open('http://www.website.net');
}
else if (choice == 'C') {
window.open('http://www.website.net');
}
else {
window.open('http://www.website.net');
}
}
关于javascript - 使用 JavaScript 有条件地打开表单提交页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458634/