Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript charAt() doesn't like user input that isn't zero

this may be a stupid question or a typo but I'm going to ask anyway... I have the following form and when the form is submitted I want to check all the values of the input type="number" and make sure that if the user has for some reason put a zero at the start of the input, for example 01, 025, 0100, to remove the first zero as long as the value isn't zero. A simple piece of JavaScript made even easier with a jQuery selector. Note that all the text boxes here are type="number" not type="text" and please note my input

enter image description here

Here's my code:

$('input[type=number]').each(function(){
    // only if the string is not zero
    if(this.value.charAt(0) == "0" && this.value != "0"){
        this.value = this.value.substring(1);
    }   
});

However when I came back to test my form fully I noticed my code didn't work! So I added the following to write to the console to check what was going on:

console.log("typeof:" + typeof(this.value) + " " + this.id + " char:" + this.value.charAt(0) + " val:" + this.value )

And this gave me the following output, notice the last 4 items that don't have the value of zero:

enter image description here

Why am I not getting the this.value.charAt(0) when the user has changed the default value of zero?

like image 877
Mike Sav Avatar asked Sep 06 '26 13:09

Mike Sav


1 Answers

It seems that there are spaces in your value. Trim it before comparing (e.g. with jquery, or see here if you don't want to include jquery just for that):

$('input[type=number]').each(function(){
    // only if the string is not zero
    var myval = $.trim(this.value);
    this.value = myval.replace(/^[0]+/g,"");

});

The above solution removes arbitrary leading zeroes, that part was taken from this answer to a similar question.

like image 62
codeling Avatar answered Sep 08 '26 03:09

codeling



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!