Reputation: 143
How to disable enable button with change of input value. I want to enable button with Change in #second
read-only input field, by changing its value remotely or from other input field.
$(document).ready(function(){
$('#button').attr('disabled',true);
});
$(document).on('change keyup blur','#first',function(){
var second= $('#second').val();
if($(this).val() != '' ){
sum = parseFloat($(this).val()) + parseFloat(second);
$('#second').val(sum);
}
});
$("#second").on('change',function(){
var second= $(this).val();
var third= $('#third').val();
if (second == third) {
$('#button').attr('disabled',false);
} else {
$('#button').attr('disabled',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="first" placeholder="first">
<input type="number" id="second" value="5" readonly>
<input type="number" id="third" value="10" readonly>
<input type="button" id="button" value="button" />
Upvotes: 0
Views: 3057
Reputation: 76
Try this
https://www.w3schools.com/code/tryit.asp?filename=G5YTJB50T072
In your code you used keyup, change, blur which makes calculation incorrect and alway use jquery code like change function inside document.ready.
Thank You
<script>
$(document).ready(function(){
$('#button').attr('disabled',true);
$("#second").on('change',function(){
var second = $(this).val();
var third = $('#third').val();
if (second == third) {
$('#button').attr('disabled',false);
} else {
$('#button').attr('disabled',true);
}
});
});
$(document).on('keyup','#first',function(){
var second= $('#second').val();
if($(this).val() != ''){
sum = parseFloat($(this).val()) + parseFloat(second);
$('#second').val(sum);
$('#second').val(sum).trigger('change');
}
});
</script>
Upvotes: 1
Reputation: 42054
Your issue is in this line:
$('#second').val(sum);
Changing an input value does not trigger a change event. So, you can trigger it by yourself:
$('#second').val(sum).trigger('change');
$('#button').attr('disabled', true);
$(document).on('change keyup blur', '#first', function () {
var second = $('#second').val();
if ($(this).val() != '') {
sum = parseFloat($(this).val()) + parseFloat(second);
$('#second').val(sum).trigger('change');
}
});
$("#second").on('change', function () {
var first = $("#first").val();
var second = $(this).val();
var third = $('#third').val();
if (second == third) {
$('#button').attr('disabled', false);
} else {
$('#button').attr('disabled', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="first" placeholder="first">
<input type="number" id="second" value="5" readonly>
<input type="number" id="third" value="10" readonly>
<input type="button" id="button" value="button">
Upvotes: 0