#1
  1. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    573
    Rep Power
    51

    Strange JavaScript Behavior


    Hi

    I am struggling with the following portion of a JavaScript script:
    Code:
    $('.unitCount').keyup(function(e){ 
    ....
    var unitCount = $(this).val(); 
    var unitSubId = $(this).attr('data-id'); 
    var unitPrice = {'standard': +$(this).attr('data-standard'), 'member': +$(this).attr('data-member'), 'joining': +$(this).attr('data-member')};  
    var member_price_limit = $(this).attr('data-member_price_limit');		
    var grandTotal = 0.00; 
    alert ("Mbr Limit: " + member_price_limit);	
    alert ("Count: " + unitCount);	
    if (unitCount > member_price_limit){
    alert("Max Exceeded");
    }
    .....
    });
    In this case, "member_price_limit" = 2. When I start typing into the form field, the two alerts for "member_price_limit" and "unitCount" pop up with the correct values. However the alert "Max Exceeded" ONLY pops up if the FIRST TYPED digit exceeds "member_price_limit", i.e. "3" or "4". However if the first digit is "1" and the second digit is "1" (i.e. the value in the field is "11", the "Max Exceeded" alert is not displayed, in spite of the fact that "unitCount" alert correctly says the value is "11".

    What am I doing wrong?

    Thanks
  2. #2
  3. Backwards Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,896
    Rep Power
    9646
    .val()s and .attr()s are text values. If you compare them then you'll be doing so as strings, not as numbers.

    If they're supposed to be numbers then you should parseInt() them, but using + (like on the unitPrice line) is generally fine too if you know the user didn't enter anything invalid.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2004
    Location
    Boston, MA USA
    Posts
    573
    Rep Power
    51
    Originally Posted by requinix
    .val()s and .attr()s are text values. If you compare them then you'll be doing so as strings, not as numbers.

    If they're supposed to be numbers then you should parseInt() them, but using + (like on the unitPrice line) is generally fine too if you know the user didn't enter anything invalid.
    Thanks!

    I really need to sit down and learn JavaScript properly in stead of "trial-and-error" modifications to existing scripts!

IMN logo majestic logo threadwatch logo seochat tools logo