Milk_QD
Milk_QD

Reputation: 135

Passing an element into a javascript function which is then added to EventListener

I am trying to write a small javascript to validate the input of type = "number" in the form of my website. Basically, this function is trying to make sure the maximum length of input allowed is no longer than the arguments I have passed in. I wrote the function to take in two arguments, one is an html element and the other is the maxlength. However, after I add this function to the input element, it does not seem to be working. Please take a look and tell me where I have gone wrong and what concepts I missed.


/* Show submit button only when the form has been validated */
/* Variables */
var form = document.querySelector(".resForm");
var resFormBtn = document.querySelector(".submitButton");
var numInput = document.querySelector("#numberInput");

function showSubmitButton() {
    if (form.checkValidity() === true) {
        resFormBtn.style.display = "block";
    }
}

function validateNumInput(maxlength, ele) {
    if (ele.length > maxlength) {
        ele.value = ele.value.slice(0, maxlength);
    }
}

form.addEventListener("change", showSubmitButton, false);

numInput.addEventListener("input", function () {
    validateNumInput(8, numInput);
}, false);

Upvotes: 0

Views: 35

Answers (1)

Mactavish
Mactavish

Reputation: 66

if (ele.length > maxlength)

There is something wrong here. ele is a referenced node, it has no such a property called "length", therefore the code inside the condition will never trigger.

simply change it to

ele.value.length > maxlength

the code will just do fine

Upvotes: 2

Related Questions