Coder Perfect

How can I stop buttons from filling out forms?

Problem

The remove button on the following page submits the form in Firefox, but the add button does not.

How can I keep the form from being submitted if I use the delete button?

Asked by Khanpo

Solution #1

You’re making use of an HTML5 button. The reason for this is that this button’s default behavior is submit, as indicated in the W3 specification, which can be found here: HTML5 Button from the W3C

As a result, you must define its type explicitly:

<button type="button">Button</button>

in order to override the submit type that is used by default. I merely want to draw attention to the reason for this.

Answered by Metafaniel

Solution #2

Set the button type as follows:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

When an exception happens in the event handler, this will prevent them from triggering a submit action. Then, make sure your removeItem() function doesn’t throw an exception:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the difference: your earlier code pulled an HTML element from the jQuery set and then attempted to execute a jQuery method on it, which produced an exception, causing the button to behave as expected.

In any case, there’s another route you may take with this… Use jQuery to set up your event handlers, and use the preventDefault() method on the event object to stop the default action right away:

$(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
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique allows you to keep all of your code in one place, making it easier to debug… it also allows you to build a fallback by changing the button’s type back to submit and handling the event server-side – this is known as unobtrusive JavaScript.

Answered by Shog9

Solution #3

I needed something similar a long time ago… and I got it.

So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).

I’ll use a simple form with simply two fields and a submit button as an example.

Keep in mind what you want: It must be possible to submit it without any checks using JavaScript. If the user presses such a button, however, validation must be performed and the form delivered only if the validation is passed.

Normally, everything would begin with something similar to this (I eliminated all unnecessary information):

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>

Notice how the form tag lacks an onsubmit=”…” attribute (remember it was a condition not to have it).

The issue is that regardless of whether onclick returns true or false, the form is always submitted.

It appears to work if I replace type=”submit” with type=”button,” but it does not. It never sends the form, but this is simple to fix.

So here’s what I came up with:

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>

Also, on the function Validator, where return True; is, I add a JavaScript submit statement that looks like this:

function Validator(){
   //  ...bla bla bla... the checks
   if(                              ){
      document.getElementById('theFormID').submit();
      return(true);
   }else{
      return(false);
   }
}

The id=”” is only for getElementById in JavaScript, while the name=”” is only for it to appear in POST data.

It functions in the manner that I require.

This is only for those who don’t need an onsubmit function on their form but still want to perform some validation when a user presses a button.

Why is there no need for an onsubmit tag on the form tag? Easy, I need to do a submit on other JavaScript portions, but I don’t want any validation.

The rationale for this is that if the user is the one who submits, I want and need the validation to be done, but if it is JavaScript, I occasionally need to submit even though such validations would prevent it.

It may seem unusual at first, but consider the following scenario: a login… with some constraints… such as not allowing PHP sessions or cookies!

As a result, any link must be transformed to a form submit in order to prevent the login data from being lost. It must also work if no login has been completed. As a result, no link checking is required. However, if the user does not enter both fields, user and pass, I want to display a message to them. As a result, if one is missing, the form should not be submitted! That is the issue.

See the issue: the form must only be sent if one field is empty and the user has pushed a button, but it must be able to be sent if it is a JavaScript code.

If I work on the form tag’s onsubmit, I’ll need to know if it’s the user or another JavaScript. Because no parameters may be supplied, it is not possible to do so directly, hence some people add a variable to indicate whether or not validation is required. The first step in the validation function is to verify that the variable value is correct, and so on… Too convoluted, and the code does not express what is truly desired.

As a result, the solution is to remove onsubmit from the form tag. Insead placed it on the button, where it is most needed.

On the other hand, why put onsubmit code when I don’t require onsubmit validation conceptually? I’m desperate for button validation.

Not only is the code more apparent, but it is also where it needs to be. Just keep in mind that: – I don’t want JavaScript to validate the form (that must always be done by PHP on the server side); – I want to show the user a message stating that all fields must be filled in, which necessitates the usage of JavaScript (client side)

So, why do some people believe (or tell me) that onsumbit validation is required? No, I’m not doing any onsumbit validation on the client side. Why not just let it be implemented? I’m just doing stuff when a button is pressed.

That code and style, on the other hand, do an excellent job. I just put: in any JavaScript where I need to send the form: in any JavaScript where I need to send the form: in any JavaScript where I need to send

document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there

And it bypasses validation when it isn’t required. It simply transmits the form and redirects to another website, etc.

However, if the user hits the submit button (aka type=”button” rather than type=”submit”), the form is validated before being submitted, and if it is not legitimate, it is not sent.

I hope this discourages others from attempting long and intricate code. If onsubmit isn’t required, use onclick instead. However, please remember to modify type=”submit” to type=”button” and to use JavaScript to submit().

Answered by z666zz666z

Solution #4

I agree with Shog9, but I think I’d go with:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools, the functionality of the button> tag varies depending on the browser.

Answered by poundifdef

Solution #5

Using jQuery, you can easily acquire the reference of your buttons and prevent them from propagating, as shown below:

 $(document).ready(function () {
    $('#BUTTON_ID').click(function(e) {

            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            return false;
    });});

Answered by Ata Iravani

Post is based on https://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms