Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

forms - checking each required input for empty value with jQuery

I am checking for each required fields in a form. I tried this but it only works for the first input. How can I make it work for each input?

if($('[required]').val() != ''){ 
        $('.button1').fadeIn(0);
        $('.button2').fadeOut(0);
}else{
    $('.button1').fadeOut(0);
    $('.button2').fadeIn(0);
}

EDIT: for more context, here's another function I had below this to apply whenever they change and HTML code.

$('[required]').change(function() {
if($('[required]').val() != ''){ 
        $('.button1').fadeIn(0);
        $('.button2').fadeOut(0);
    }else{
    $('.button1').fadeOut(0);
    $('.button2').fadeIn(0);
}
});

HTML

I have bunch of inputs like these:

<input type="text" id="title" name="title" value="" required>
<input type="text" id="size" name="size" value="" required>
<input type="text" id="length" name="length" value="" required>

buttons:

<a class="button1" style="display:none" >button 1</a>
<a class="button2">button 2</a>

So I want to check for empty fields when it the page loads and whenever they change.

BTW, I don't have a form tag around these because it's for mobile and didn't think it's really necessary, if that makes any difference.

Thanks again!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This?

$( ':input[required]', yourForm ).each( function () {
    if ( this.value.trim() !== '' ) {
        // ...
    }
});

where yourForm is a reference to the FORM element (you can also use a selector here). This is the context - you only want to search for fields inside the form.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...