Reputation: 4956
In my html structure, I have plus, minus and an input field. When there is any change in my input field, I want to alert 'change occured'. So, when I change the value in my input box by typing or using the up or down arrows then it is giving me an alert. But I have written some code to change the value of input field when I click on the anchor tags with class plus or minus. So, the value is changing when I use the anchor tags but the change function is not being triggered. And hence not getting any alert. So, can anyone please let me know why change is not working here.
HTML:
<div class="quantity">
<a href="javascript:void(0)" class="minus">-</a>
<input type="number" step="1" name="quantity" value="2" title="Qty" class="input-text qty text" size="4">
<a href="javascript:void(0)" class="plus">+</a>
</div>
JQuery:
$(".plus").click(function() {
var text = $(this).prev("input");
var va = parseInt(text.val(), 10) + 1;
text.attr('value',parseInt(text.val(), 10) + 1);
});
$(".minus").click(function() {
var text = $(this).next("input");
if(text.val() > 0){
var va = parseInt(text.val(), 10) - 1;
text.attr('value',parseInt(text.val(), 10) - 1);
}
});
jQuery to detect change of input:
jQuery(document).ready(function($) {
$(document).on( 'change', '.quantity .qty', function() {
alert('change occurred');
});
});
What I have tried
I have already tried: .trigger('change') and also used keyup and input but nothing helped.
Upvotes: 0
Views: 2693
Reputation: 459
try this..
Start observing 'input' event instead of 'change'.
jQuery('#some_text_box').on('input', function() {
// do your stuff
});
OR
jQuery('#some_text_box').on('input propertychange paste', function() {
// do your stuff
});
Upvotes: 0
Reputation: 3760
Change your code as follow. You need to trigger()
a .change()
event.
$(".plus").click(function() {
var text = $(this).prev("input");
var va = parseInt(text.val(), 10) + 1;
text.attr('value',parseInt(text.val(), 10) + 1);
text.trigger("change");
});
$(".minus").click(function() {
var text = $(this).next("input");
if(text.val() > 0){
var va = parseInt(text.val(), 10) - 1;
text.attr('value',parseInt(text.val(), 10) - 1);
}
text.trigger("change");
});
Upvotes: 1
Reputation: 337570
The change
event is not fired when the element value is updated programmatically. In that case you need to trigger the event manually:
$(".plus").click(function() {
var $text = $(this).prev("input");
var value = parseInt($text.val(), 10) + 1;
$text.val(value).change();
});
$(".minus").click(function() {
var $text = $(this).next("input");
var value = parseInt($text.val(), 10) - 1;
$text.val(Math.max(0, value)).change();
});
Note that it's considered better practice to use val()
when working with input
types, over setting the attr()
.
Upvotes: 2