Angel Politis Angel Politis - 3 months ago 10
Javascript Question

No characters are typed in an HTML input

I'm creating an Object to handle my HTML inputs and apply different restrictions to each of them, but I'm currently stuck at the phase of limiting my character input to a specific number.

More specifically, the exact problem I'm currently facing is the inability of my input to accept any typed in characters.

Code:



/*----- JavaScript -----*/
function Input (selector) {
var
self = this,
element = document.querySelector(selector);

/* Properties */
this.maxLength = 32;

/* Methods */
this.onerror = function (callback) {
if (callback instanceof Function) return callback;
};
this.onsuccess = function (callback) {
if (callback instanceof Function) return callback;
};

element.onkeypress = function () {
return self.maxLength >= this.length;
};
};

var myInput = new Input("#text");
myInput.maxLength = 4;

<!----- HTML ----->
<input id = "text" type = "text"/>





What I want to achieve at this point is to restrict an input to 4 characters by setting:

myInput.maxLength = 4;


What do I have to change in my code in order to accomplish this?

Answer

The issue with input not being allowed is

  return self.maxLength >= this.length;

which results in return false. this.length should be this.value.length; also operator should be > without = to not reach .value.length of 5

 return self.maxLength > this.value.length;

/*----- JavaScript -----*/
function Input(selector) {
  var
    self = this,
    element = document.querySelector(selector);

  /* Properties */
  this.maxLength = 32;

  /* Methods */
  this.onerror = function(callback) {
    if (callback instanceof Function) return callback;
  };
  this.onsuccess = function(callback) {
    if (callback instanceof Function) return callback;
  };

  element.onkeypress = function() {
    return self.maxLength > this.value.length;
  };
};

var myInput = new Input("#text");
myInput.maxLength = 4;
<!----- HTML ----->
<input id="text" type="text" />

Comments