skip to Main Content

I have a form and I’m trying to have a button to zero out all the fields. Can’t use a ‘reset’ type button, as there are proper default values there, populated externally.

It’s incredibly basic, and I’ve stripped out any complication I can think of, but it isn’t working. It’s generated by a jinja template. When I click, however, absolutely nothing happens. No feedback in the logs, no change in the input field numbers. What amI missing?

<html>
  <head>
    ...
        <script>
      function zero_out() {
        document.getElementsByClassName("itemCount").value=0;
      }
    </script>

  </head>
  <body>
      <form method="post">
                    <label for="thing">thing</label>
                    <input type="number"  pattern="d*"
                      name="thing" style="width: 40px;"
                      class="itemCount"
                      placeholder="0"
                      value=""></input>
                    <br />
           ...
        <button onclick="zero_out()" type="button" class="button">ZERO</button>
    </form>
        
     

2

Answers


  1. If you’re only resetting one input, just use document.querySelector to get the element. (document.getElementsByClassName returns a HTMLCollection of all elements with the specified class.)

    document.querySelector('input.itemCount').value = '0';
    
    Login or Signup to reply.
  2. Just reset it with looping for collections of getElementsByClassName like this:

    function zero_out() {
      let items = document.getElementsByClassName("itemCount");
      Array.from(items).forEach((elm)=>{
        elm.value = 0;
      });
    }
    

    Full code:

    <html>
    
    <head>
        <script>
            function zero_out() {
               let items = document.getElementsByClassName("itemCount");
               Array.from(items).forEach((elm)=>{
                  elm.value = 0;
               });
            }
        </script>
    
    </head>
    
    <body>
        <form method="post">
            <label for="thing">thing</label>
            <input type="number" pattern="d*" name="thing" style="width: 40px;" class="itemCount" placeholder="0" value="5" />
            <label for="thing2">thing 2</label>
            <input type="text" pattern="d*" name="thing2" style="width: 40px;" class="itemCount" placeholder="0" value="3" />
            <br />
            <button onclick="zero_out()" type="button" class="button">ZERO</button>
        </form>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search