1

I have two inputs where I am checking to make sure that they are not empty before the form submits.

My issue is that it only validates #from_date. Is the issue that .val will only check the last id in the list?

    $('#submitDates').click(function () {
      // Get the fields you want to validate
      var name = $("#to_date, #from_date");

      // Check if field is empty or not
      if (name.val()=='') {
        alert ('Please Select Dates')
        return false;
      } ;

     }); 
    }); 
1
  • When you call .val() on a collection of multiple elements, it returns the value of the first element in the collection. This is in the first sentence of the documentation. Commented May 3, 2013 at 23:48

2 Answers 2

2

Any specific reason you're hooking on .click and not .submit?

You can iterate through the selected elements and check for a violating element using .each

var found = false;
$("#to_date, #from_date").each(function(i,name){
      // Check if field is empty or not
      if (!found && $(name).val()=='') {
        alert ('Please Select Dates')
        found = true;
      } ;
});
return !found;
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer, but it just submits the form even when both are empty. There is a small syntax error also on the last }
@KeithPower I fixed the syntax error, the point was to get you on your way I didn't test the script. I updated the answer (using .val() works on jQuery objects, each runs on the underlying DOM elements, I added a $() around the element).
0

In your example var name = $("#to_date, #from_date"); is giving you a collection of two inputs and by doing if (name.val()=='') jQuery is checking only the first element in the collection, so it's not working. You may try this

$('#submitDates').click(function () {
    var name = $("#to_date, #from_date");
    if ( name[0].value == '' || name[1].value == '' ) {
        alert ('Please Select Dates');
        return false;
    }
});

In the above example name[0].value refers to the first element and name[1].value refers to the second element. If you want to use jQuery's val() method then you can use it like $(name[0]).val() and $(name[1]).val().

Also you should consider to use submit event of the form instead of button's click event.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.