15

I've been looking around for a solution to this, but can't seem to find any examples that work for me. Here's what I've got so far:

$("#register-form").submit(function(){
            if($(".required input").val() == '') {
                alert("Please fill in all the required fields (indicated by *)");
                $(".required").addClass('highlight');
                // $('input[type=submit]', this).attr('disabled', 'disabled');
                return false;
            }
        });

For some reason, when I submit the form with none of the required fields filled in (there are two), then it works, but if one of them is filled out, it doesn't.

Any ideas why?

Thanks

osu

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Osu
  • 1,137
  • 2
  • 18
  • 34
  • What does your html form look like? – Ryan May 04 '11 at 16:19
  • (html5: use required attribute in input tag)Possible duplicate of http://stackoverflow.com/questions/17865148/using-jquery-to-prevent-form-submission-when-input-fields-are-empty/39609587#39609587 – Elnaz Sep 21 '16 at 07:10

9 Answers9

44

The problem with your code is that you're only testing the first field you've got flagged as required. $(".required input") only returns the first input in your form that matches that selector.

This loops through all the inputs in the form that are flagged required (according to your selector). If it finds one with a value of '' then it sets the submit function to return false and highlights the blank fields. It also removes the highlight class from fields that are now valid but were previously invalid in an early form submit attempt.

$("#register-form").submit(function(){
    var isFormValid = true;

    $(".required input").each(function(){
        if ($.trim($(this).val()).length == 0){
            $(this).addClass("highlight");
            isFormValid = false;
        }
        else{
            $(this).removeClass("highlight");
        }
    });

    if (!isFormValid) alert("Please fill in all the required fields (indicated by *)");

    return isFormValid;
});
Ryan
  • 6,756
  • 13
  • 49
  • 68
  • Thanks Ryan - I had to do some fixing (unclosed parenthesis in places), but your solution made most sense to me. Here's the code I ended up with: http://www.pastie.org/1864757 Thanks to everyone for their help! – Osu May 04 '11 at 16:54
  • Ah I guess I did miss a couple closing braces/parens... glad I could help. – Ryan May 04 '11 at 16:56
8
$("#register-form").submit(function() {
  $('.required input').each(function() {
    if ($($this).val() == '') { 
      $(this).addClass('highlight');
    }
  });

  if ($('.required input').hasClass('highlight')) {
    alert("Please fill in all the required fields (indicated by *)");
    return false;
  }
} 

Give that a shot.

EDIT Moved the alert so users don't get their faces blown off with alert messages, good catch.

David Fells
  • 6,678
  • 1
  • 22
  • 34
2

Simple Solution !:

 function checkForm(){
        $("input.required").css("border","1px solid #AFAFAF");
        $("input.required[value=]").css("border-color","red");
        if($("input.required").val().length<2)return false;
        return true;
    }
Andri
  • 553
  • 4
  • 20
1

Maybe your condition should be this:

if($("input.required").val() == '')... //Pay attention to the selector

Cause your selector was finding all inputs children of .required

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • This will only return the `val()` of the first matched input, just like the OP's code. The only difference is that yours assumes a different html structure. – Jeff B May 04 '11 at 16:41
1

Basing on David Fell's answer, (that has an error, in my opinion) you could do this:

$("#register-form").submit(function() {
  $('.required input').each(function() {
    if ($(this).val() == '') {           
      $(this).addClass('highlight');
    }
  });

  if ($('.required input.highlight').size() > 0) {
    alert("Please fill in all the required fields (indicated by *)");
    return false;
  }
} 
Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
  • IMHO this is bad because it will alert the end user each time a required field is found that is blank. – Ryan May 04 '11 at 16:49
0

This code get all form fields with select list & checkbox etc.

var save_prms = $("form").serializeArray();
    $(save_prms).each(function( index, element ) {
        alert(element.name);
        alert(element.val);
    });
Sandeep Sherpur
  • 2,418
  • 25
  • 27
0

If the

$(".required input")

is matching more than one element, then

$(".required input").val() == ''

probably won't do what you're expecting.

Mu Mind
  • 10,935
  • 4
  • 38
  • 69
0

You can't reference the values of all the form inputs like that.

var valid = true;
$('.required input').each(function(){
   if( $(this).val() == '' ){
      valid = false;
      $(this).addClass('highlight');
   }
});

The forms plugin will do this for you, by the way.

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
0

name of the input or id in this case used id of the input

HTML:

<input type="text" id="id"... />

JQUERY:

if (!$("#id").val()) {
   do something...
}
obinoob
  • 677
  • 4
  • 13
  • 34