开发者

javascript conditional returning unexpected result

I'm doing a simple number comparison on the keyUp event of an input field. For some reason, I'm not getting the expected result, and I can't figure out why. What should happen is that if the user-entered number is larger than that stored in the html attribute, the background should turn red, otherwise it stays white. Simply entering '9' will turn the background red. ??

var admin = $('input[name="diskStorage"]').attr('data-adminstorage'); // 2097152000

$('#new-user input[name="diskStorage"]').keyup(function(){

    if(admin < $(this).val())
        $(this).css('background','red');
    else
        $(this).css('background','white');
});

When I debug these values, if(2097152000 < 549) is returning true. Here's the html, in case that makes any difference:

<form action="administrate.php" method="post" id="new-user">
<table><tbody><tr>
...
  </tr><tr>
    <td>Disk Storage Limit:</td>
    <td>
   <input type="text" data-adminStorage="2097152000" name="diskStorage" value="" /> megaBytes<br />
    <span id="info"></span></td>
...
  </tr></tbody></table>

Here it is live: http://jsfiddle.net/JMC_Creative/dqAJj开发者_Go百科/2/


.attr and .val() return String objects - use the unary + operator to convert it to a numeric value.

var admin = $('input[name="diskStorage"]').attr('data-adminstorage');
admin = +admin;

if(admin < +$(this).val()) {
   //...
}


Try adding a /1 after retrieving the admin value, to make it a number not a string.

var admin = $('input[name="diskStorage"]').attr('data-adminstorage')/1;

Edit: also on the this.val:

$(this).val()/1;


They are probably both strings. You should convert them to numbers first:

var admin = Number($('input[name="diskStorage"]').attr('data-adminstorage')); // 2097152000

$('#new-user input[name="diskStorage"]').keyup(function(){

    if(admin < Number($(this).val()))
        $(this).css('background','red');
    else
        $(this).css('background','white');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜