Question

I made this code to validate a checkout form. But there is one field which not need to be required. All the other fields are required. How can I modify my code to exclude this field, and only add the class 'valid' if this field is filled in and not empty.

Has anyone tips for me to do this?

// Validate checkout fields
$( '#checkout-data input' ).each( function() {
    $( this ).change( function() {
        if( $( this ).val().length < 1 ) {
            $( this ).removeClass( 'valid' ).addClass( 'invalid' );
        } else {
            $( this ).removeClass( 'invalid' ).addClass( 'valid' );     
        }
    });
});
Was it helpful?

Solution

Add a required class to the required input fields and then change your code like,

$( '#checkout-data input.required' ).each( function() {
    $( this ).change( function() {
        if( this.value.length < 1 ) {
            $( this ).removeClass( 'valid' ).addClass( 'invalid' );
        } else {
            $( this ).removeClass( 'invalid' ).addClass( 'valid' );     
        }
    });
});

Also, there is no need of $.each() like,

$('#checkout-data input.required').change( function() {
    if( this.value.length < 1 ) {
        $( this ).removeClass( 'valid' ).addClass( 'invalid' );
    } else {
        $( this ).removeClass( 'invalid' ).addClass( 'valid' );     
    }
});

Live Demo

OTHER TIPS

Use not() method or :not selector:

$( '#checkout-data input' ).not('.exclude')each( function() {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top