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:
The problem is that
jQuery("#phrase").lengthgets the amount of ELEMENTS matching the jQuery selector. Rather usejQuery("#phrase").val().lengthto get the amount of characters entered.