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开发者_StackOverflow中文版 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.
精彩评论