checking each required input for empty value with jQuery

后端 未结 5 1788
感情败类
感情败类 2020-12-19 11:36

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($(\'[require         


        
5条回答
  •  渐次进展
    2020-12-19 12:02

    The "change" event works for the SELECT box and RADIO button elements but not for the INPUT elements. You've to use the "focus/blur" events for handling the input fields, in your case the "blur" event suits perfectly.

    If you want to process many elements using jQuery then it's better to go with the CLASS based operations, in your case just add a same class "required" for all the input fields and make the operations on those fields using that class.

    I've adjusted your code blocks as I specified above, check them once and then let me know if the updated code also not working for you, updates code blocks are:

    HTML Code

    
    
    
    
    
    button 2
    

    JS Code

    $('.required').blur(function() {
      var empty_flds = 0;
      $(".required").each(function() {
        if(!$.trim($(this).val())) {
            empty_flds++;
        }    
      });
    
      if (empty_flds) {
        $('.button1').fadeOut(0);
        $('.button2').fadeIn(0);
      } else {
        $('.button1').fadeIn(0);
        $('.button2').fadeOut(0);
      }
    });
    

    You can also check the working code directly here.

提交回复
热议问题