Search code examples
jqueryrequired

validate required fields are filled on modal with jquery


I am dynamically populate some text boxes in modal popup, when submitting the form I need to check required fields are filled.

I have tried with two method but both are not working..

If you want to check here is the full code http://jsfiddle.net/nsk21/f52nLfrj/

This how try 1:

 $(document).on('click', '#catSave', function(){
    var countValid = 0 ;
    totRequFileds = 0;

    $('#catCreatForm').find('input').each(function(){
        alert($(this).attr('type'));
        if(!$(this).prop('required')){
            if ( this.value.trim() !== '' ) {                           
                countValid++;                                           
            }else{      
                $(this).focus();
                return false;
            }
            totRequFileds++; 
        } else {

        }
    });       
    alert(' totRequFileds:'+totRequFileds +' | '+countValid);
});

try 2:

      $( ':input[required]', '#catCreatForm' ).each( function () {
            alert($(this).attr('name'));
            if ( this.value.trim() !== '' ) {                           
                countValid++;                                           
            }else{      
                $(this).focus();
                return false;
            }
            totRequFileds++; 
        }); 

Solution

  • You could have not comented out those lines in the fiddle, i have changed that lines a little

    $(document).on('click', '#catSave', function(){
    	var countValid = 0 ;
    	totRequFileds = 0;
    	$( ':input[required]', '#catCreatForm' ).each( function () {
    		totRequFileds++;
    		alert($(this).attr('name'));
    		if ( this.value.trim() !== '' ) {							
    			countValid++;											
    		}else{		
    			$(this).focus();
    			//return false;
    		}
    	});
    	if( countValid != totRequFileds){
    		alert('Please fill out all required fileds totRequFileds:'+totRequFileds +' | '+countValid);
          return false;
    	}
        alert(' totRequFileds: '+totRequFileds +' | '+countValid);
    });