user1334616
user1334616

Reputation:

listen for changes in a textbox

I'm trying to write some code for a personalised products page on my site. My aim is to have a textbox allowing the user to enter a personal message to go on the product and use jQuery to determine the price based on the number of characters entered. Then print the price back on screen.

I'm not sure which even listener I should be using. "keyup" seems to stop after the first character entered and "change" only works when the user click off the text box. I would like the code to increase the price as the user types. Any tips on where I'm going wrong?

<script type="text/javascript" language="javascript">
     $(document).ready(function()  {
        jQuery("#phrase").change( function () {     
                 var length = jQuery("#phrase").length;
                 var price = length * 2.5;


                 jQuery("#price").html(price);
    });

});
</script>

jsFiddle here:

http://jsfiddle.net/WVHaT/8/

Upvotes: 1

Views: 3399

Answers (4)

Willem Mulder
Willem Mulder

Reputation: 13994

I would use keyup, since it is fired after the textbox's value has been updated (in contrast to keydown that is fired before the textbox's value is updated) and also directly after the key is up (in contrast to the .change event which only fires when the input loses focus).

That it does seem to only fire for one key is another problem, which the answer of FarligOpptreden solves!

Upvotes: 0

FarligOpptreden
FarligOpptreden

Reputation: 5043

The problem is that jQuery("#phrase").length gets the amount of ELEMENTS matching the jQuery selector. Rather use jQuery("#phrase").val().length to get the amount of characters entered.

Upvotes: 1

Rnk Jangir
Rnk Jangir

Reputation: 741

change your code from

var length = jQuery("#phrase").length;

to

var length = jQuery("#phrase").val().length;

and call jQuery("#phrase").keyup

Upvotes: 1

James Kyburz
James Kyburz

Reputation: 14453

$('#phrase').keyup(function() {
  var length = this.value.length * 2.5;
  $('#price').html(length);
});

http://jsfiddle.net/jameskyburz/WVHaT/

Upvotes: 2

Related Questions