skip to Main Content

I have following HTML code, where I add items to cart and then finally click submit.

 <div class="form-group">
   <div>
     <select id="available-options" multiple>
         <option value="option1">Option 1</option>
         <option value="option2">Option 2</option>
         <option value="option3">Option 3</option>
      </select>
     <button id="add-button" aria-label="Add">Add</button>
   </div>
 </div>
<div class="box-footer">
     <button type="submit" class="btn btn-default">Cancel</button>
     <button type="submit" class="btn btn-info pull-right">Update</button>
</div>

I have below Javascript

  window.onload = function () {
      const addButton = document.getElementById("add-button");

       addButton.addEventListener("click", () => {
       const selected = availableOptions.selectedOptions;
       for (let i = 0; i < selected.length; i++) {
          const option = selected[i];
          selectedOptions.appendChild(option);
         }
     });
   }

When I click add button, both button events are getting fired!

2

Answers


  1. The default type of button element is submit that causes the submission of the form. You can either specify the button type="button" or prevent the default behavior using event.preventDefault().

    Demo:

    <form>
      <div class="form-group">
        <div>
          <button id="add-button" aria-label="Add">Add</button>
        </div>
      </div>
    
      <div class="box-footer">
        <button type="submit" class="btn btn-default">Cancel</button>
        <button type="submit" class="btn btn-info pull-right">Update</button>
      </div>
    </form>
    <script>
      window.onload = function () {
        const addButton = document.getElementById("add-button");
    
        addButton.addEventListener("click", (event) => {
          event.preventDefault(); //prevent the form from submitting
    
          //other code here
          console.log("Add button clicked");
        });
      };
    </script>
    Login or Signup to reply.
  2. Try to use event.stopPropagation() inside the event handler.

    This issue might be come because of the way of Javascript manage the events. Javascript by default follows the events bubbling. So here, when the target event is being completed, it will also called its next parent level event handler or better to say, event bubbling up to its parent and it will go till the final DOM event. So, to prevent this, we have to specifically mention event.stopPropagation() inside the handler method.

    I think above answer will help you. I’m also giving a reference link on this topic, please check this reference link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search