0

I have four email fields in a form, and I want that the user when using the submit button, it's required to fill out a minimum of one field.

This is the 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> 

How can I do it?

3 Answers 3

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(); } }); 
Sign up to request clarification or add additional context in comments.

3 Comments

i think this will consider string "0" as an empty input, you may want to be more explicit with your filter condition.
string '0' is ok (because !!0 == false but !!'0' == true), but sure, I'd add !! before the return value in the filter.
Thank you, Im need to know if the email entered is a regex email. This not works for me :(
1

One way: concatenate the four values and if it's not blank then you're sure one of them has been filled in.

Comments

0

This should work:

<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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.