表格html
<form action="" method="post" name="add_new_report" id="add_new_report" enctype="multipart/form-data" onsubmit="return AddNewReport(this)">
<div class="field">
<div class="field_180">Cheque</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cheque" id="cheque" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_180">Cash</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cash" id="cash" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_210"> </div>
<div class="field_222">
<input type="submit" id="Submit" name="Submit" value="Submit" />
</div>
<div class="clear"></div>
</div>
</form>
以这种形式,用户应该输入支票或现金字段怎么可能?我不想两者都是强制性的。
答案 0 :(得分:0)
如果您完全不关心IE&lt; 9,您可以使用以下内容。 (否则替换不在IE中工作的代码,有些代替)
function oneShouldHaveData(ids) {
var elements = [];
//convert ids to elements (map no IE<9)
elements = ids.map(function (id) {
return document.querySelector('#' + id);
});
//returns true if any element matches expression (some no IE <9)
return elements.some(function (element) {
//could be validation for anything (greater 0 etc.)
return !!element.value;
});
}
//just submit setup :)
document.querySelector('#add_new_report').addEventListener('submit', function () {
console.log(oneShouldHaveData(['cheque', 'cash']));
});
答案 1 :(得分:0)
只需将此功能添加到标题中:
<script>
function validateForm()
{
var x=document.forms["add_new_report"]["cheque"].value;
var y=document.forms["add_new_report"]["cash"].value;
if ((x==null || x=="") && (y==null || y==""))
{
alert("At least one entry should be filled");
return false;
}
else
return true
}
</script>
并更改以下字段:
onsubmit="if(validateForm()) return AddNewReport(this)"
您还可以在validateForm函数中包含AddNewReport,并且只返回validate(this)函数。