Reputation: 83
I'm using the following code to execute a value update based on a code entered. But it returns wrong.
Ex: If the promo code is to reduce the price by 10, and the current total is 100, this returns 80. which should be 90.
jQuery(document).ready(function() {
$('#promo-code').keyup(function() {
if ($("input:text[name='promo-code']").val() == "intro") {
var promoval = parseFloat($("input:text[name='total']").val());
$("#total").val(promoval-10);
}
});
Upvotes: 0
Views: 1992
Reputation: 4956
I hope you set the html correctly, and the keyup functionality should work just fine. But you would also like to check other methods as mentioned in other answers here. I would suggest that you go for change
method.
jQuery(document).ready(function() {
$('#promo-code').keyup(function() {
if ($("input:text[name='promo-code']").val() == "intro") {
var promoval = parseFloat($("input:text[name='total']").val());
$("#total").val(promoval-10);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="promo-code" type="text" id="promo-code"/>
<input name="total" type="text" value="100" id="total"/>
Upvotes: 0
Reputation: 4400
Try some else instead of keyup
like focusout
as below. Because when you are using keyup
it gets fire every keyup event.
$(document).ready(function() {
$('#promo-code').focusout(function() {
if ($("input:text[name='promo-code']").val() == "intro") {
var promoval = parseFloat($("input:text[name='total']").val());
$("#total").val(promoval-10);
}
});
});
Check below snippet for reference.
$('#total').val(100);
$('#promo-code').focusout(function() {
if ($(this).val() == "intro") {
var promoval = parseFloat($('#total').val());
$("#total").val(promoval - 10);
} else {
alert('invalid promo');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="promo-code">
<input type="text" id="total">
Upvotes: 0
Reputation: 1198
An improvised solution for your problem:
jQuery(document).ready(function() {
$('#promo-code').change(function() {
if ($(this).val() == "intro") {
var promoval = parseFloat($("input:text[name='total']").val());
$("#total").val(promoval-10);
}
}
});
Upvotes: 0