Keith Power
Keith Power

Reputation: 14141

javascript stop button onClick from submitting form

I have two button inside a form that I don't want to submit the form but add and remove table rows. One button is dynamically added.

I have tried many ways to prevent the submission but none seem to work. When I was getting the button by id and using an event listener it was ok but that did not work with button that get added after age load. I am trying to find a solution that will work with buttons. The one that loaded on page load and the ones that get added dynamically with JavaScript.

                <table id="conditions-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Level</th>
                            <th></th>
                        </tr>
                        <tr>
                            <td>
                                <input id="condtitions-input"></input>
                                <select id="condtitions-level">
                                    <option value="Mandatory">Mandatory</option>
                                    <option value="Important">Important</option>
                                    <option value="Support">Support</option>
                                </select>
                            </td>
                            <td>
                                <button id="add-condtition" onclick="addCondition(e); return false;">Add Conditions</button></td>
                            </td>  
                        </tr>
                    </thead>
                </table>
            </fieldset>
            <?= $this->Form->button(__('Submit')) ?>
            <?= $this->Form->end() ?>
        </div>
    </div>
</div>
<script>
    var counter = 0;

    function addCondition(e){
        e.preventDefault()

        var table = document.getElementById("conditions-table");
        var row = table.insertRow(2);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        var condtionsInput = document.getElementById("condtitions-input");
        var condtionsInputValue = condtionsInput.value;
        condtionsInput.value = "";

        var selectedLevel = document.getElementById("condtitions-level");
        var selectedLevelValue = selectedLevel.value;
        
        cell1.innerHTML = `<input type="text" name="strategies_conditions[${counter}][name]" value=" ${condtionsInputValue}"></input>
                            <select>
                                <option ${(selectedLevelValue == "Mandatory") ? 'selected="selected"' : ""} value="Mandatory">Mandatory</option>
                                <option ${(selectedLevelValue == "Important") ? 'selected="selected"' : ""} value="Important">Important</option>
                                <option ${(selectedLevelValue == "Support") ? 'selected="selected"' : ""} value="Support">Support</option>
                            </select>`;
        cell2.innerHTML = "<button class='remove-condition' onclick="removeCondition()">X</button></td>";

        counter++;

        return false;
    };

    function removeCondition() {
       // event.target will be the input element.
       var td = event.target.parentNode; 
      var tr = td.parentNode; // the row to be removed
      tr.parentNode.removeChild(tr);       
    };

Upvotes: 1

Views: 2353

Answers (4)

Brandon Wegner
Brandon Wegner

Reputation: 76

All you really need to do is add:

 <input type="submit" onclick="event.preventDefault();">

You probably want to handle it though so in total you'd probably do something more like this:

  <script>
function myFunction(){
  if (confirm("Are you sure you want to ...? This action cannot be undone.")) {
  document.getElementById("myForm").submit();
  }

}
  </script>
  <form method="post" action="/test" id="myForm">
  <input type="submit" onclick="event.preventDefault();myFunction();">

  </form>

This allows the user to click ok to proceed or cancel to not have it submit the form.

Upvotes: 0

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

Just don't insert the argument e inside the onclick event in the markup you can apply an event using JavaScript like the following

btn.onclick = e => {
  e.preventDefault();
}
<form>
  <input type="text" name="" placeholder="Name">
  <input type="submit" name="" id="btn">
</form>

or you can simply make a onclick event return false like the following

<form>
  <input type="text" name="" placeholder="Name">
  <input type="submit" name="" id="btn" onclick="return false">
</form>

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89224

The default type of a button is "submit"; just override that behavior by setting it to "button".

cell2.innerHTML = "<button type='button' class='remove-condition' onclick='removeCondition()'>X</button></td>";

You also need to define event as a parameter of the event handler function.

function removeCondition(event) {
      // event.target will be the input element.
      var td = event.target.parentNode; 
      var tr = td.parentNode; // the row to be removed
      tr.parentNode.removeChild(tr);       
};

Upvotes: 2

Eslam Adel
Eslam Adel

Reputation: 1189

to add an event to an element that doesn't exist yet on the DOM you need to know about event.target

here is a sample that might help you

document.addEventListener( "click", listenerFunction );

function listenerFunction(event){
    var element = event.target;
    // here you check for that auto generated element
    if(element.tagName == 'A' && element.classList.contains("someBtn")){
        console.log("hi");
    }
}

Upvotes: 0

Related Questions