0

I am new to jquery and javascript but I wondered if anyone had any nice ideas about how I can show the user an error (alert) if they try to submit the form when both fields are empty.

Here is the code I am working with: http://jsfiddle.net/spadez/uaZkV/1/

I believe the relevant bit of the code is here:

$('#searchform').on('submit', function (event) {
    var form = this;

    event.preventDefault(); // stop the submission

    processLocation(function (success) {
        if (success) { // if the geocoding succeeded, submit the form
            form.submit()
        }
    });

In sudo code I'm after something like this:

If #kw & #loc == 0 
    then alert "Cannot leave fields blank"
4
  • if( $(this).find('.class-of-input1').val() == '' ) Commented May 23, 2013 at 15:58
  • you asked almost the exact same question a few days ago! stackoverflow.com/questions/16583453/… Commented May 23, 2013 at 16:03
  • To be fair, that was a different question and the answers to that do not answer this question Commented May 23, 2013 at 16:20
  • If I understood you right my answer should help you Commented May 23, 2013 at 16:32

2 Answers 2

1

Assuming the IDs of the input fields are: kw , loc and when I say 'ID' I mean:

<input type='text' name='bla' id='kw'>
<input type='text' name='bla' id='loc'>

You can do this:

if( $('#kw').val() == '' && $('#loc').val() == '')
{
 alert("Cannot leave fields blank");
}
Sign up to request clarification or add additional context in comments.

Comments

0

The nicest way to validate your form would be JQuery validation plugin

http://jqueryvalidation.org/

Anyway, you should not stop submiting because there is an error. First you validate and if there is no error you submit

5 Comments

"First you validate and if there is no error you submit" - isn't that what his snippet does?
He stops the automatic submission from the button click, then he validates, then he submits if the validation succeeds if there is no error in the callback from processLocation.
sure but why letting submitting if you stop the submit behind ?
Thank you for the reply but this feels like using a hammer to open a peanut
use the plugin... it is a nice way to validate on client-side otherwise on your submit button you call your own function that validate and return false or true..it is just that... simple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.