我在表单中有4个电子邮件字段,我希望用户在提交按钮时,其所需填写最少1个字段。
这是html:
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
我该怎么做?
答案 0 :(得分:3)
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// all the fields are empty
// show error message here
// this blocks the form from submitting
event.preventDefault();
}
});
答案 1 :(得分:1)
一种方法:连接四个值,如果它不是空白,那么你肯定其中一个已被填写。
答案 2 :(得分:0)
这应该有效:
<script type="text/javascript">
function check_recipients(form){
var empty = true;
$('#invitation_form_recipients input').each(function(){
if($(this).val() != ''){ empty = false; }
});
if(empty){
alert('You have to fill in at least one recipient!');
return false;
}else{
form.submit();
}
}
</script>
<form id="new_invitation" class="new_invitation" onsubmit="check_recipients(this); return false;" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>