Way to set maxlength on input based on data in another field of same form in html5?

Viewed 779

How can I set the maxlength attribute in my text input field equal to the value the user enters in the number input field in the same form?

<form action="/action_page.php">
  <input id="number" type="number" value="20" max="40">
  <input type="text" id="username" name="username" maxlength="10"><br><br>
  <input type="submit" value="Submit">
</form>

I'm guessing this maybe requires JavaScript?

2 Answers

You can set the maxlength property on the input event.

document.querySelector("#number").addEventListener("input", function(e){
  document.querySelector("#username").maxLength = this.value;
});
<form>
  <input id="number" type="number" value="20" max="40">
  <input type="text" id="username" name="username" maxlength="20"><br><br>
  <input type="submit" value="Submit">
</form>

Yes, this requires JavaScript. You would do something like this:

document.querySelector('#number').addEventListener('input', (e) => {
  e.target.closest('form').querySelector('[name="username"]').maxLength = e.target.value;
});

JSFiddle: https://jsfiddle.net/63cpv8rk/

Here, we add an event handler for the input event for the element selected by #number. (You should avoid using these ID attributes though... they clutter up the global scope needlessly.)

Then on input, we find the parent form, and then select the input by name. Finally, we set its max length to the value that was just put in our field.

Related