Check if input empty on submit

后端 未结 9 685
谎友^
谎友^ 2020-12-25 08:36

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\")         


        
相关标签:
9条回答
  • 2020-12-25 09:06
    $("#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.

    0 讨论(0)
  • 2020-12-25 09:06

    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

    0 讨论(0)
  • 2020-12-25 09:10

    If the

    $(".required input")
    

    is matching more than one element, then

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

    probably won't do what you're expecting.

    0 讨论(0)
  • 2020-12-25 09:12

    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);
        });
    
    0 讨论(0)
  • 2020-12-25 09:16

    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;
    });
    
    0 讨论(0)
  • 2020-12-25 09:18

    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...
    }
    
    0 讨论(0)
提交回复
热议问题