1

I'm trying to create an order form for a class project where there are 6 items and each item requires a quantity entered. I have the input type as number and the scroll bar displays when clicking into the field but I also want to make sure users cannot manually input a number over 10. I realized we cannot use "getElementById" since id's must be unique and will only fire on the first element with that Id. I've been playing around with getElementByClassName but it's not firing at all. All inputs in the table have the same class, name, and iD assigned. Any suggestions/ideas why this isn't working?

Javascript:

var quant = document.getElementsByClassName("Quantity");
quant.addEventListener("blur", checkquant);
var message = document.getElementsByClassName("quantmsg");
 function checkquant() {                                                       
      if (quant < 11) {    
        message.textContent = "";                        
    } else {                                                                          
        message.textContent = "Maximum Quantity of 10";
    }                                                                                 
    }

HTML (one input sample out of the 6 within a table):

    <tr>
    <td><input type="checkbox" name="DesktopPC" value="DesktopPC">
        <label for="DesktopPC">Desktop PC</label>
    </td>
    <td><label for="QuantityD">Quantity:</label>
        <input class="Quantity" type="number" value="0" min="0" max="10" onfocus="inputfocus();">
        <div class="quantmsg"></div>
    </td>
</tr>
rexbex
  • 23
  • 2
  • Short answer is that you're trying to add an event listener to to collection. The message will be set to an HTMLCollection, which you can then iterate over. Also note, more modern to use `querySelectorAll()` const quant = document.querySelectorAll(".Quantity"); quant.forEach(field => { field.addEventListener("blur", checkquant); }); You can shorten it further too: document.querySelectorAll(".Quantity").forEach(field => field.addEventListener("blur", checkquant)); – jonlink Jun 26 '20 at 18:16
  • Not sure who closed this question, but the linked answer is only helpful if you aren't a beginner and this is a beginner question. – jonlink Jun 26 '20 at 18:17
  • Thanks! I'll give this a try and see how it goes. My question was closed and linked to another question, I'll check out those answers as well. – rexbex Jun 29 '20 at 14:46

0 Answers0