Reputation: 745
I want to disable input2 if the user starts typing a value into input1.
If there is no value in input1 (for example if the value is deleted), I also want input2 to be re-enabled.
Here's what I wrote so far, but it's not working.
<input id="input1" type="text">
<input id="input2" type="text">
<script>
$( document ).ready(function() {
if($('#input1').val())
{
$('#input2').prop('disabled', true);
}
});
</script>
Upvotes: 2
Views: 2458
Reputation: 21
This answer included the good aspects of above answers
<input id="input1" type="text">
<input id="input2" type="text">
$(document).ready(function () {
$('#input1').attr("disabled", true);
$('#input2').on("input propertychange", function (e) {
if ($('#input2').val()) {
$('#input1').removeAttr('disabled');
} else {
$('#input1').attr('disabled', true);
}
});
});
Upvotes: 0
Reputation: 26971
Bind "input" and "propertychange" like so:
let secondInput = $('#input2'); // Cache the jQuery element
$("#input1").on(
"input propertychange",
event => secondInput.prop(
'disabled',
event.currentTarget.value !== "")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text">
<input id="input2" type="text">
This works even with copy/paste, dragging in, and all other methods.
propertychange
is not a must, but it is for IE support.
Upvotes: 4
Reputation: 189
If you wan't the second input to be disabled when the first is changed you can listen for keyup and change the disabled to true. In the example i only do it if the first input is not empty.
<input id="input1" type="text">
<input id="input2" type="text">
<script>
$( document ).ready(function() {
$('#input1').on('keyup', function(e){
if(e.target.value.length > 0){
$('#input2').prop('disabled', true);
}else{
$('#input2').prop('disabled', false);
}
});
});
</script>
Upvotes: 0