Reputation: 67
I have two input fields on my form - I'd like to only allow users to enter field2 if field 1 has valid data. How can I achieve this using jQuery.
Thanks in advance
Upvotes: 2
Views: 1938
Reputation: 42143
Yes.
For example if you want to enable 2nd textbox only when 1st textbox is not empty.
$('#text1').blur(function(){
if( $(this).val() == '' ) { // for example empty textbox not allowed
$('#text2').val('').attr('disabled','disabled');
} else {
$('#text2').removeAttr('disabled');
}
});
Upvotes: 0
Reputation: 76003
//cache the second field to make the event handler perform faster
var field2 = document.getElementById('field2');
$('#one').on('change', function () {
//check to make sure the value is "valid"
if (this.value == '') {
//if not valid then disable the input
field2.disabled = true;
} else {
//if valid then enable the input
field2.disabled = false;
}
});
Here is a demo: http://jsfiddle.net/gL8Jq/
Note that .on()
is new in jQuery 1.7 and in this case is the same as .bind()
: http://api.jquery.com/on
Upvotes: 1
Reputation:
$('id_field_2').change(function(){
if ( !is_field_valid($('id_field1').val()) ) {
$('id_field_2').val('');
}
});
you can use "change" or other keybord event line keydown, keypress.
Upvotes: 0
Reputation: 66693
What data do you want to have in field1, i.e. in what format? Depending on that you need to write a validate function, that you should call on field1's onblur. This validate function should check the data in field1, and enable/disable field2 appropriately.
i.e. Something like:
$('#field1').blur(function() {
var data = $('#field1').val();
var valid = false;
// ... do you validation here ...
$('#field2').attr('disabled', !valid);
});
Upvotes: 1
Reputation: 13756
$('#input-one').change(function(){
if($(this).val() == "valid value")
$('#input-two').removeAttr('disabled', 'disabled');
else
$('#input-two').attr('disabled', 'disabled');
});
I hope this helps.
Upvotes: 3
Reputation: 17454
Bind to the change
event of field 1 and perform validation. Then, set the "disabled" attribute of field 2 based on the results of your validation.
Upvotes: 0
Reputation: 298582
This basic structure might work for you:
$('#field1').change(function() {
if (isValidData($(this).val()) {
$('#field2').removeAttr('disabled');
} else {
$('#field2').attr('disabled', 'disabled');
}
}).change();
I don't think the whole disable
business is very clean. Does anyone know of a cleaner solution?
Upvotes: 0