简体   繁体   中英

parseInt doesn't work

in my current source code textbox value is 1. when I try alert(isNaN(obj.text()) it returns false that is expected but after parseInt when I write alert(a); it returns NaN

minus.click(function () {
     var a = 1; if (!isNaN(obj.text())) a = parseInt(obj.text()); 
     if (a > 1) a -= 1; obj.text(a);
});

what is the problem?

Edit: this is the full code:

<input type="text" class="basket-txt" value="1" />


jQuery.fn.basket = function (options) {
    var defaults = {
    }
    options = jQuery.extend(defaults, options);
    this.each(function () {
        var $this = $(this);
        $this.height(32).css({ 'line-height': '32px', 'font-weight': 'bold', 'width':'40px', 'text-align':'center', });
        var tbl = $('<table border="0" style="border-spacing:0px;float:left;">').appendTo($this.parent());
        var tr1 = $('<tr>').appendTo(tbl);
        var plus = $('<div class="basket-plus">');
        $('<td>').append(plus).appendTo(tr1);
        $('<td>').append($this).appendTo(tr1);
        var minus = $('<div class="basket-minus">');
        $('<td>').append(minus).appendTo(tr1);
        var tr2 = $('<tr>').appendTo(tbl);
        $('<td>').appendTo(tr2);
        $('<td>').appendTo(tr2).append($('<div>').addClass('add-to-basket'));
        $('<td>').appendTo(tr2);
        $this.keypress(function (e) { if (e.which < 48 || e.which > 57) e.preventDefault(); });
        minus.click(function () {

            var a = 1; if (!isNaN($this.text())) a = parseInt($this.text()); 
            if (a > 1) a -= 1; $this.text(a);
        });
        plus.click(function () {
            var a = 1; if (!isNaN($this.text())) a = parseInt($this.text());
            if (a < 1000000) a += 1; $this.text(a);
        });
    });
}

actually I knew I could correct the code and it would work my concern was to understand why isNaN returns false but parseInt returns NaN

You get the value of an <input> with .val() , not .text() .

The isNaN() function returns false for isNaN("") . Why? Because when "" (the empty string) is converted to a number, it's 0 . Pass a non-number to isNaN() and the first thing it does is coerce the value into a number.

It's kind-of pointless to try isNaN() before parseInt() anyway, since parseInt() will tell you when it can't parse a nice-looking integer. Note however that parseInt() doesn't care if there's garbage at the end of the input.

If you want to convert a string to a number when it's a valid string representation of a number, and NaN when it isn't, you can use

var myNumber = +myString;

That'll accept numbers with fractional parts and exponents too, so you'd have to either truncate that to just an integer or check to see if it is one:

var myNumber = +myString;
if (isNaN(myNumber))
  // not a valid number
else if (myNumber !== Math.floor(myNumber))
  // not an integer
else
  // yaay!

The jQuery text() method will take all the descendent text nodes of an element and combine them into a single string.

An input element can't have descendant nodes of any kind. Its current value is exposed via the value property, which you can read with the val() method in jQuery.

You shouldn't use parseInt without a radix, especially with free form input. You might get octal or hex data instead of a decimal.

parseInt($this.val(), 10)
minus.click(function () {
    // let's parse the integer first
     var num = parseInt( obj.val(), 10 );

     // then later, we can check if it's NaN
     if ( !isNaN(num) && num > 1 ) {
        num -= 1;
        obj.val(num);
     }
});



actually I knew I could correct the code and it would work my concern was to understand why isNaN returns false but parseInt returns NaN

isNaN doesn't work the way it should. There is type coercion going on.
isNaN will convert the value to a number first. An empty string will be converted to a 0

Number("") === 0; // true

0 is obviously not NaN, so it returns false.

parseInt doesn't do type coercion, it parses the value differently.

Check this question and this other question for reference.

当第一个非空白字符无法转换为数字时,parseInt 返回 NaN。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM