tags:

views:

55

answers:

2

Hi,

I have 2 textboxes and a label on my page. The 2 textboxes will contain numeric values. The label text will be the product of the 2 textbox values. Is there a way to do this using JQuery so that the value can get updated when I edit the textboxes without having to do a postback?

Also the textboxes may contain values with commas in it: e.g. 10,000. Is there a way I can extract the number from this so that it can be used to calculate the label value.

Thanks in advance,

Zaps

A: 
$('#SecondTextbox').keyup(function() {
   var t1 = $('#FirstTexbox').val();
   var t2 = $(this).val();
   var result = t1+t2;
   $('#resultLabel').html(result);
});

This could do the trick, or you could have it on a click event with some link element. This would also not have any page refresh.

$('#checkButton').click(function() {
   var t1 = $('#FirstTexbox').val();
   var t2 = $('#SecondTextbox').val();
   var result = t1+t2;
   $('#resultLabel').html(result);
});

Link could be something like,

<a id="checkButton" title="Check your result">Check</a>

And with that you would have the css settings of 'cursor:pointer;' to make it seem a proper link.

duckbox
You'll need to throw in some parseInt and some replacing of commas to turn the strings into numbers. Something like `parseInt($('#FirstTexbox').val().replace(',',''))` should work to turn each value into a number that can then be added together
Dan F
+1  A: 

I can't add comments to other answers yet, so I'll just post an update here.

The original question involved product, which means multiplication, so here's a version that allows for unlimited textboxes and completes the multiplication.


function makeInt(text) {
  return parseInt(text.replace(',', ''));
}
$(function(){
  //hook all textboxes (could also filter by css class, if desired)
  //this function will be called whenever one of the textboxes changes
  //you could change this to listen for a button click, etc.
  $("input[type=text]").change(function(){
    var product = 1;
    //loop across all the textboxes, multiplying along the way
    $("input[type=text]").each(function() {
      product *= makeInt($(this).val());
    });
    $("#display-control-id").html(product);
  });
});
ilowe