我有一组 4 个单选按钮,其中有两个提交按钮,即一个的类型为“提交”,另一个的类型为“按钮”:
<form id='myform' method="POST">
<label style="font-family: sansationregular;">Choose a time frame:</label><br/>
<input type="radio" name="time" value="t1"><label style="margin-left: 10px;font-family: sansationregular;; vertical-align: middle;"> Today</label> </input>
<input type="radio" name="time" value="t2"><label style="margin-left: 10px;font-family: sansationregular;; vertical-align: middle;"> Last 1 Week</label> </input>
<input type="radio" name="time" value="t3"><label style="margin-left: 10px;font-family: sansationregular;; vertical-align: middle;"> Last 1 Month</label> </input>
<input type="radio" name="time" value="t4"><label style="margin-left: 10px;font-family: sansationregular;; vertical-align: middle;"> Last 1 Year </label></input>
<br/><br/>
<input type="submit" class="k" align="middle" id="btn1" value="Download Raw Data" style="font-family: sansationregular; vertical-align: middle;" />
<input type="button" class="k" id="btn2" value="Most Frequent Words">
</td>
</form>
我已使用以下脚本验证了第一个按钮的选择:
var form = document.getElementById('myform');
var btn = document.getElementById('btn2');
form.onsubmit = function() {
if ($(this).find('input[type="radio"]:checked').length > 0) {
form.action="{{ url_for('choice') }}"
form.target = '_blank';
} else {
alert("Please choose the desired option!");
form.action="{{ url_for('home') }}"
form.target='_self'
}
};
但是在接下来的验证中使用与上面相同的方法不起作用。下面的代码是我想要验证单选按钮是否被选择/不针对第二个提交按钮的地方。
btn.onclick = function() {
form.target = '_blank';
form.action="{{ url_for('wordcloud') }}"
form.submit();
}
感谢任何帮助。谢谢!
最佳答案
您的代码不起作用,因为,
直接调用 HTMLFormElement.submit() 方法时,不会引发任何提交事件(特别是,不会运行表单的 onsubmit 事件处理程序),也不会触发约束验证。
查看此链接以获取更多信息,https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
或者,您也可以这样做。希望这可以帮助。
var form = document.getElementById('myform');
var btn = document.getElementById('btn2');
function inputLength() {
return $('#myform').find('input[type="radio"]:checked').length > 0;
}
function submitForm() {
if (inputLength()) {
form.action="{{ url_for('choice') }}"
form.target = '_blank';
} else {
alert("Please choose the desired option!");
form.action="{{ url_for('home') }}"
form.target='_self'
}
}
form.onsubmit = submitForm;
btn.onclick = function() {
form.target = '_blank';
form.action="{{ url_for('wordcloud') }}"
submitForm();
form.submit();
}
关于javascript - 检查单选按钮选择是否针对 2 个提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50170667/