简体   繁体   中英

Check empty value for all fields

I want If was value for all inputs go to url # ( <form action="#".... ) else do not go. but in this code it work just for first field, i want it work for all fields .(i can not use from ajax call or preventDefault or window.location (Because one from field is input:file). how can fix it?

See demo: http://jsfiddle.net/jGu4e/

<form action="abc.html" method="POST" class="submit">
    <input type="text" name="name"><br>
    <input type="text" name="name"><br>
    <input type="text" name="name"><br>
    <button id="cli">Submit</button>
</form>



$('.submit').submit(function() {
    var input = $(this).closest('form').find('input[type="text"]');
  if (!$(input).val()){
    var cssObj={'border-radius':'5px',border:"none","box-shadow":"0 0 1px 1px red",outline:"none",background:"#ffc4c4"};
    $('input[type="text"]').css(cssObj);
    return false;
  };
});

Your problem is really twofold. Firstly, your selector can/will return multiple fields. Secondly, you need to return false from the .submit call when any one of these does not have a value.

This jQuery should do the trick:

$('.submit').submit(function() {
        var input = $(this).closest('form').find('input[type="text"]');
        var result = true;
        input.each(function(){           
            if (!$(this).val()){
              var cssObj={'border-radius':'5px',border:"none","box-shadow":"0 0 1px 1px red",outline:"none",background:"#ffc4c4"};
              $(this).css(cssObj);
              result = false;
            };
        });
        return result;
    });

As demonstrated by your updated jsfiddle here: http://jsfiddle.net/T9YBu/1/

EDIT: There are still defects in this code. Such as if a user does not enter a value it becomes red. If the user subsequently fills in a value and clicks submit it stays red. Easy enough to fix, but really this is why you should use a pre-tested validation plugin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM