質問

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.

I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?

my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000

function limitNumberOfCharacters() {
    x = my_var.toString().length;
    $('.my_input_class').attr('maxlength', x);
}

limitNumberOfCharacters(); //this gets called often

EDIT: http://jsfiddle.net/mDw6f/

役に立ちましたか?

解決

EDITTTT:

You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)

Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.

Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.

Cheers

Real Fiddle Example

他のヒント

Try using this fiddle:

Working Demo

Use the html input like I did in the code, no need to specify the maxlength attribute to it.

<input type="text" class="my_input_class"/>

and the script

my_var = 25; //this var changes often, can go down to 0 or up to 1000000000

function limitNumberOfCharacters() {
    x = my_var.toString().length;
    $('.my_input_class').attr('maxlength', x);
}

limitNumberOfCharacters();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top