skip to Main Content

Let’s say I have a select with some option values

<select name="select">
   <option value="item-one">Item one</option>
   <option value="item-two">Item two</option>
</select>

<input type="number" name="quantity">

If I selected Item one, I want the input number to have a max allowed value of 3, otherwise if Item two if selected it would be 4.

I tried looping it using foreach loop but wont return the right result

2

Answers


  1. You can use this

    <option value="item-one">Item one</option>
       <option value="item-two">Item two</option>
    </select>
    
    <input id="quantity" type="number" name="quantity">
    
    <script>
        document.getElementById('selectItem').addEventListener('change', function(e) {
            var quantityInput = document.getElementById('quantity');
            if (e.target.value === 'item-one') {
                quantityInput.max = 3;
            } else if (e.target.value === 'item-two') {
                quantityInput.max = 4;
            }
        });
    </script>
    
    Login or Signup to reply.
  2. You cannot do that in PHP but with JavaScript you can.

    I use an array where the index matches the selectedIndex of the select

    I trigger on load and I also reduce if the select is changed

    I added an input event handler too, because min/max only works with the spinners AND the submit event.

    Alternative for my input test is to set and trigger custom validity on the input field

    window.addEventListener("DOMContentLoaded", () => {
      const sel = document.querySelector("[name=select]");
      const numberField = document.querySelector("[name=quantity]");
      sel.addEventListener("change", (e) => {
        numberField.max = [3,4][e.target.selectedIndex];
        if (+numberField.value > +numberField.max) numberField.value = numberField.max;
      });
      sel.dispatchEvent(new Event('change')); // initial value
      numberField.addEventListener("input",(e) => {
        const val = numberField.value;
        if (+val > +numberField.max) numberField.value = numberField.max;
      })
      numberField.addEventListener("blur",(e) => {
        const val = numberField.value;
        if (isNaN(parseFloat(val)) || !isFinite(val)) numberField.value = 0; // field allows [e.-+] remove on blur if no digits
      })
    });
    <select name="select">
      <option value="item-one">Item one</option>
      <option value="item-two">Item two</option>
    </select>
    
    <input type="number" name="quantity">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search