简体   繁体   中英

jQuery change text box value not working

I'm trying to display total price in sum label by multiplying qtyTxt value (user entered) with price . But it doesn't work, the if statement is never reached.

<input type="text" name="qtyTxt" value="1" size="2" style="width: 25px"/>
<label id="price">${adClicked.price}</label>
<label id="sum">${adClicked.price}</label>
<input type="hidden" name="id" value="${adClicked.id}"/>

<script>
$(".qtyTxt").bind('change', function () {
    var sum=$(("#price").val())* ($(this).val());
    $("#sum").val('Rs.'+sum);
});
</script>

There are no errors in the console and $("#sum").val('Rs.'+sum); works fine.

1) Use parseInt() or parseFloat() The parseInt() function parses a string and returns an integer.

2) Another mistake Don't use val() for label instead of use text() for label

var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);

code be

$(".qtyTxt").bind('change', function () {
  var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
   $("#sum").text('Rs.'+sum);
});

Two issue:

1) You have error in your code, $(("#price").val()) should be $("#price").text() or $("#price").html()

2) You need to parse the values before doing mathematical calculation:

var sum=parseInt($("#price").text(),10)*parseInt($(this).val(),10) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM