how to check if input field is empty

前端 未结 7 986
别那么骄傲
别那么骄傲 2020-12-30 01:36

I\'m making a form with inputs, if the input type is empty then the button submit is disabled but, if the input fields is with length > 0 the submit button is enabled

<
相关标签:
7条回答
  • 2020-12-30 02:02

    Why don't u use:

    <script>
    $('input').keyup(function(){
    if(($('#eng').val().length > 0) && ($('#spa').val().length > 0))
        $("#submit").prop('disabled', false);
    else
        $("#submit").prop('disabled', true);
    });
    </script>
    

    Then delete the onkeyup function on the input.

    0 讨论(0)
  • 2020-12-30 02:04

    use .val(), it will return the value of the <input>

    $("#spa").val().length > 0
    

    And you had a typo, length not lenght.

    0 讨论(0)
  • 2020-12-30 02:06

    As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

    var input = $.trim($("#spa").val());
    
    if (input) {
        // Do Stuff
    }
    

    You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

    So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

    $(".test").each(function () {
        $(this).keyup(function () {
            $("#submit").prop("disabled", CheckInputs());
        });
    });
    

    which would then call the following and return a boolean value to assign to the disabled property:

    function CheckInputs() {
        var valid = false;
        $(".test").each(function () {
            if (valid) { return valid; }
            valid = !$.trim($(this).val());
        });
        return valid;
    }
    

    You can see a working example of everything I've mentioned in this JSFiddle.

    0 讨论(0)
  • 2020-12-30 02:07

    if you are using jquery-validate.js in your application then use below expression.

    if($("#spa").is(":blank"))
    {
      //code
    }
    
    0 讨论(0)
  • 2020-12-30 02:12

    This snippet will handle more than two checkboxes in case you decide to expand the form.

    $("input[type=text]").keyup(function(){
        var count = 0, attr = "disabled", $sub = $("#submit"), $inputs = $("input[type=text]");  
        $inputs.each(function(){
            count += ($.trim($(this).val())) ? 1:0;
        });
        (count >= $inputs.length ) ? $sub.removeAttr(attr):$sub.attr(attr,attr);       
    });
    

    Working Example: http://jsfiddle.net/sr4gq/

    0 讨论(0)
  • 2020-12-30 02:15

    Use trim and val.

    var value=$.trim($("#spa").val());
    
    if(value.length>0)
    {
     //do some stuffs. 
    }
    

    val() : return the value of the input.

    trim(): will trim the white spaces.

    0 讨论(0)
提交回复
热议问题