我制作了此代码以验证结帐表单。但是有一个领域不需要。所有其他字段都是必需的。如何修改我的代码以排除此字段,并且只有在填写此字段且不为空时才添加“有效”类。
有没有人提示我这样做?
// 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' );
}
});
});
答案 0 :(得分:3)
将required
课程添加到required input fields
,然后将代码更改为
$( '#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' );
}
});
});
此外,不需要$.each()
喜欢,
$('#checkout-data input.required').change( function() {
if( this.value.length < 1 ) {
$( this ).removeClass( 'valid' ).addClass( 'invalid' );
} else {
$( this ).removeClass( 'invalid' ).addClass( 'valid' );
}
});
<强> Live Demo 强>
答案 1 :(得分:0)
使用not()方法或:not selector:
$( '#checkout-data input' ).not('.exclude')each( function() {