我正在尝试使用下面的代码。基本上,我需要的是在文本字段(预定日期)不为空且未选中复选框(关闭)时发出警报。因此,如果两者都为空,则表单可以提交,但如果文本字段有值,并且未选中复选框,则提醒。警报应该有“继续”或“取消”选项。
<script>
function validate() {
var valid = true;
var checkbox = document.getElementById('close').value;
var text = document.getElementById('dateshipped').value;
if(!(checkbox || text))
valid = confirm("Checkbox isn't checked. \n Continue?");
return valid;
}
</script>
我的表格:
<form id="form" name="form" method="post" onsubmit="return validate();">
<input type="checkbox" name="close" id="close" value="Yes"><label for="close" class="css-label-rma" title="Close this">Close this</label>
<input type="text" name="dateshipped" id="dateshipped" class="datefield" /></label>
<input type="submit" value="submit" />
</form>
这里是jsfiddle:http://jsfiddle.net/jvvu6vo0/
答案 0 :(得分:0)
我担心你有几个问题
1)onsubmit
是一个表单事件,而不是button
事件。你应该
<form id="form" name="form" method="post" onsubmit="return validate();">
2)函数validateSubmit
不存在。名称标识validate
3)您的提交按钮必须是submit
4)您必须使用checked属性而不是值
document.getElementById('close').checked;
答案 1 :(得分:0)
submit
。您validate
函数中有一些错误。您应该检查checkbox.checked
而不是checkbox.value
,并且应该检查text
字符串的长度。
This fiddle should work for you.
function validate() {
var valid = true;
var checkbox = document.getElementById('close');
var text = document.getElementById('dateshipped').value;
if( ! checkbox.checked || text.length)
valid = confirm("Checkbox and text are empty. \n Continue?");
return valid;
}
var form = document.getElementById('form');
form.onsubmit = function(e) {
if ( ! validate()) {
e.preventDefault(); // This will stop the form from submitting.
return false;
}
alert('I am submitted.');
}
&#13;
<form id="form" name="form" method="post">
<input type="checkbox" name="close" id="close" value="Yes"><label for="close" class="css-label-rma" title="Close this">Close this</label>
<input type="text" name="dateshipped" id="dateshipped" class="datefield" /></label>
<input type="submit" value="submit" />
</form>
&#13;