0

I'm writing a bit code code that will calculate a price for a personalised product based on user input. In this case they have the option of choosing a message ("happy birthday" or "happy anniversary" or something similar) to appear in the finished product.

The price should be calculated based on the number of characters in the message. So the price should increase by £4 for every character, but should only increase by £2 for every blank space.

I having problems getting my code to go through each character in order to determine how much it should be charging. Any ideas where I'm going wrong?

this might help if my explanation isn't clear enough. http://jsfiddle.net/6QhAz/1/

code:

$(document).ready(function () {
  jQuery("#phrase").keyup(function () {     
    var length = this.value.length; 
    var price;
    var message =jQuery("#phrase").val;
    for ( var i=0; i > length; i++) {
      if (this.value === " " ) {
        price + 1.50;                       
      } else {
        price + 2.50;
      };
    };

    jQuery("#price").html('Price: £'+price);
  });
});

3 Answers 3

2

Instead of iterating over the characters, just use regex to count them:

$(document).ready(function()  {
    $("#phrase").keyup(function() {      
        var value = $(this).val();
        var spaces = (value.match(/\s/g) || []).length;

        var price = 1.5 * spaces + 2.5 * (value.length - spaces);

        $("#price").html('Price: £' + price);
    });
});​

Demo: http://jsfiddle.net/6QhAz/6/

Sign up to request clarification or add additional context in comments.

Comments

1
 $("#phrase").keyup( function () {    
            var message =$("#phrase").val();        
            var length = message.length; 
            var price = 0;

            for ( var i=0; i < length; i++) {
                if (message.charAt(i) == " " ) {
                    price += 1.50;                       
                } else {
                    price += 2.50;
                };

            };

            $("#price").html('Price: &pound;'+price);

    });

Comments

1

You can iterate through a string letter by letter using the charAt method of your string:

var name_str = "hello world!";
for (var i=0; i < name_str.length; i++) {
    alert(name_str.charAt(i));
}

Live example: http://jsfiddle.net/dM7Vd/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.