MNM MNM - 2 months ago 6
HTML Question

Set the max attribute of a input box from the value of another one dynamically html

I am trying to set the max quantity of this input box to another input box but I am missing something on how to connect the two of them. Here is the one that I want the max value to change based no the current value of another input

<input id="movement-quantity" class="movement-quantity" type="number" step="1" min="0" max = "1" pattern="\d*" required>


This is the input that I want to get the value from, this value will automatically change wit other code so I am trying to listen to this one

<input id="store-from-current-quantity" class="store-from-current-quantity" type="text" disabled>


Here is the function that I am using currently

function getMaxValueForRequest()
{
var requester = document.getElementById("movement-quantity");
var currentItemAmount = parseInt(document.getElementById("store-from-current-quantity").value);
requester.max = currentItemAmount;
}


And this is at the start of the script file that the function above is in

//variables
var numberAv= parseInt(document.getElementById("store-from-current-quantity").value);
numberAv.elX.onchange = getMaxValueForRequest;

Answer

Use Element.setAttribute

Notes

  • I've manually given #store-from-current-quantity has a value in the HTML - I assume this is being set elsewhere in your app.
  • The change event listener does not fire until blur/submit/etc, so you may want to consider keydown or keyup.

I have some confusion about numberAv.elX.onchange however - why are you trying to get elX property of a Number?

I've removed the disabled attribute on the second input in this example to you can test it.

function getMaxValueForRequest() {
  var requester = document.getElementById("movement-quantity");
  var currentItemAmount = parseInt(document.getElementById("store-from-current-quantity").value);
  requester.setAttribute('max', currentItemAmount);
}


// init once to set
getMaxValueForRequest()


// listen for changes
document.getElementById("store-from-current-quantity").addEventListener('change', function(event) {
  getMaxValueForRequest()
})
<input id="movement-quantity" class="movement-quantity" type="number" step="1" min="0" max = "1" pattern="\d*" required>
<input id="store-from-current-quantity" class="store-from-current-quantity" type="text" value="5">