Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Set the type on your buttons:</p> <pre><code>&lt;button type="button" onclick="addItem(); return false;"&gt;Add Item&lt;/button&gt; &lt;button type="button" onclick="removeItem(); return false;"&gt;Remove Last Item&lt;/button&gt; </code></pre> <p>...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your <code>removeItem()</code> function so that it doesn't trigger an exception:</p> <pre><code>function removeItem() { var rows = $('form tr'); if ( rows.length &gt; 2 ) { // change: work on filtered jQuery object rows.filter(":last").html(''); $('form :hidden:last').val(''); } else { alert('Cannot remove any more rows'); } } </code></pre> <p>Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.</p> <p>FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the <a href="http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29" rel="noreferrer">preventDefault()</a> method on jQuery's <a href="http://docs.jquery.com/Events/jQuery.Event" rel="noreferrer">event</a> object to cancel the default behavior up-front:</p> <pre><code>$(function() // execute once the DOM has loaded { // wire up Add Item button click event $("#AddItem").click(function(event) { event.preventDefault(); // cancel default behavior //... rest of add logic }); // wire up Remove Last Item button click event $("RemoveLastItem").click(function(event) { event.preventDefault(); // cancel default behavior //... rest of remove last logic }); }); ... &lt;button type="button" id="AddItem" name="AddItem"&gt;Add Item&lt;/button&gt; &lt;button type="button" id="RemoveLastItem" name="RemoveLastItem"&gt;Remove Last Item&lt;/button&gt; </code></pre> <p>This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the <code>type</code> on the buttons back to <code>submit</code> and handling the event server-side - this is known as <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="noreferrer">unobtrusive JavaScript</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload