Reputation: 2539
Well I am facing a problem to handle the change event of a input
field. Because I am changing the text of the input field by another script. Consequently I am not able to catch the event.
Look, here I have 2 buttons -
and +
when I will click either -/+ then the some value is inserting inside the text box. It's a numeric value and I have manually added increment and decrements by including and reducing 1. Anyway, as my text inside the text box is changing however, I am not able to capture the event in jQuery
My code is as below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button>-</button><input type="text" id="abc" /><button>+</button>
and none of my jQuery function is capture the event.
$("#abc").change(function(){
alert();
});
$("#abc").click(function(){
alert();
});
Because I have added the text through another jQuery
helper. So how can I catch the text change event. I don't want to write down the code inside increment and decrements function. I want to keep that code intact. So is there any way I can solve this easily? Thanks in advance.
Update: Here is the update code for increment and decrements
var btn = $(this),
oldValue = $('#abc').val().trim(),
newVal = 0;
if (btn.attr('data-dir') == 'up') {
newVal = parseInt(oldValue) + 1;
} else {
newVal = parseInt(oldValue) - 1;
}
$('#abc').val(newVal);
Upvotes: 0
Views: 60
Reputation: 133403
You need to .trigger(event)
the event, events are triggered when user interacts with element.
$("#abc").change(function() {
console.log('changed', this.value);
});
$("button").click(function() {
var btn = $(this),
oldValue = $('#abc').val().trim(),
newVal = 0;
if (oldValue != '') {
if (btn.attr('data-dir') == 'up') {
newVal = parseInt(oldValue, 10) + 1;
} else {
newVal = parseInt(oldValue, 10) - 1;
}
}
$('#abc').val(newVal).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-dir="down">-</button><input type="text" id="abc" /><button data-dir="up">+</button>
Upvotes: 1
Reputation: 26949
Since the other script that is changing the input is also using jquery, the most reliable way is probably just triggering a change event manually after the input value has been updated.
$('.counter').val(oldValue + 1).trigger('change');
Upvotes: 1