Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 602
Ashkan Mobayen Khiabani Avatar asked Apr 27 '26 09:04

Ashkan Mobayen Khiabani


1 Answers

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)
like image 93
Quentin Avatar answered Apr 28 '26 23:04

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!