ahhchuu
ahhchuu

Reputation: 471

jquery .keyup event on input not firing

I am trying to have a simple addition calculation when an input is keyup'ed. Here is my html:

<tr id="a">
        <td>
            <label>A</label>
        </td>
        <td>
            <label>Results/Action Orientation (asset)</label>
        </td>
        <td class="shade">
            <input id="a_per" type="text" />
        </td>
        <td class="shade">
            <input id="a_pot" type="text" />
        </td>
        <td class="shade">
            <input id="a_tot" class="totals" type="text" disabled="disabled" />
        </td>
</tr>

And here is my jQuery for the keyup event:

$('#a_per').keyup(function() {
    if($('#a_pot').value != "") {
        var tot = this.value + $('#a_pot').value;
        $('#a_tot').value = tot;
    }
});

I am going to tailor it to fire when either #a_per or #a_pot keyup but first I want to make sure this will work.

Any help is appreciated. Thanks.

Upvotes: 2

Views: 6500

Answers (3)

Alexander
Alexander

Reputation: 23537

Another alternative:

$('#a_per,#a_pot').keyup(function() {
  var a_per = +$('#a_per').val() || 0;
  var a_pot = +$('#a_pot').val() || 0;
  $('#a_tot').val(a_per + a_pot);
});​

A working example.

Upvotes: 2

Shyju
Shyju

Reputation: 218732

use val(), not value.

$(function(){

   $('#a_per').keyup(function() {
     var item=$(this);

      if(item.val() != "") {
         var tot = parseInt(item.val()) + parseInt($('#a_pot').val());
         $('#a_tot').val(tot);
      }
   });

});

Working sample : http://jsfiddle.net/zzS3U/9/

Upvotes: 1

j08691
j08691

Reputation: 207901

Change your use of .value to .val(). You'll also want to apply parseFloat or parseInt to your addition function, otherwise you'll end up concatenating strings. Also wrap this is jQuery tags like:

$('#a_per').keyup(function() {
    if($('#a_pot').val() != "") {
        var tot = parseFloat($(this).val()) + parseFloat($('#a_pot').val());
        $('#a_tot').val(tot);
    }
});​

Upvotes: 1

Related Questions