[javascript] Stop an input field in a form from being submitted

I'm writing some javascript (a greasemonkey/userscript) that will insert some input fields into a form on a website.

The thing is, I don't want those input fields to affect the form in any way, I don't want them to be submitted when the form is submitted, I only want my javascript to have access to their values.

Is there some way I could add some input fields into the middle of a form and not have them submitted when the form is submitted?

Obviously the ideal thing would be for the input fields to not be in the form element, but I want the layout of my resulting page to have my inserted input fields appear between elements of the original form.

This question is related to javascript html forms userscripts

The answer is


Handle the form's submit in a function via onSubmit() and perform something like below to remove the form element: Use getElementById() of the DOM, then using [object].parentNode.removeChild([object])

suppose your field in question has an id attribute "my_removable_field" code:

var remEl = document.getElementById("my_removable_field");
if ( remEl.parentNode && remEl.parentNode.removeChild ) {
remEl.parentNode.removeChild(remEl);
}

This will get you exactly what you are looking for.


The easiest thing to do would be to insert the elements with the disabled attribute.

<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />

This way you can still access them as children of the form.

Disabled fields have the downside that the user can't interact with them at all- so if you have a disabled text field, the user can't select the text. If you have a disabled checkbox, the user can't change its state.

You could also write some javascript to fire on form submission to remove the fields you don't want to submit.


Do you even need them to be input elements in the first place? You can use Javascript to dynamically create divs or paragraphs or list items or whatever that contain the information you want to present.

But if the interactive element is important and it's a pain in the butt to place those elements outside the <form> block, it ought to be possible to remove those elements from the form when the page gets submitted.


You can write an event handler for onsubmit that removes the name attribute from all of the input fields that you want not to be included in the form submission.

Here's a quick untested example:

var noSubmitElements = [ 'someFormElementID1', 'someFormElementID2' ]; //...
function submitForm() {
    for( var i = 0, j = noSubmitElements.length; i < j; i++ ) {
        document.getElementById(noSubmitElements[i]).removeAttribute('name');
    }
}
form.onsubmit = submitForm;

You need to add onsubmit at your form:

<form action="YOUR_URL" method="post" accept-charset="utf-8" onsubmit="return validateRegisterForm();">

And the script will be like this:

        function validateRegisterForm(){
        if(SOMETHING IS WRONG)
        { 
            alert("validation failed");
            event.preventDefault();
            return false;

        }else{
            alert("validations passed");
            return true;
        }
    }

This works for me everytime :)


All of the above answers already said everything about (not) naming the form controls or programmatically removing them before actually submitting your form.

Although, across my research I found one other solution that I haven't seen mentioned in this post:
If you encapsulate the form controls you want to be unprocessed/not sent, inside another <form> tag with no method attribute nor path (and obviously no submit type control like a button or submit input nested in it), then submitting the parent form won't include those encapsulated form controls.

<form method="POST" path="/path">
  <input type="text" name="sent" value="..." />
  <form>
    <input type="text" name="notSent" value="..." />
  </form>
  <input type="submit" name="submit" value="Submit" />
</form>

The [name="notSent"] control value won't be processed nor sent to the server POST endpoint, but the one from [name="sent"] will.

This solution might be anecdotic but I'm still leaving it for posterity...


I know this post is ancient, but I'll reply anyway. The easiest/best way I have found is just to simply set the name to blank.

Put this before your submit:

document.getElementById("TheInputsIdHere").name = "";

All in all your submit function might look like this:

document.getElementById("TheInputsIdHere").name = "";
document.getElementById("TheFormsIdHere").submit();

This will still submit the form with all of your other fields, but will not submit the one without a name.


Add disabled="disabled" in input and while jquery remove the attribute disabled when you want to submit it using .removeAttr('disabled')

HTML:

<input type="hidden" name="test" value="test" disabled='disabled'/>

jquery:

$("input[name='test']").removeAttr('disabled');


_x000D_
_x000D_
$('#serialize').click(function () {_x000D_
  $('#out').text(_x000D_
    $('form').serialize()_x000D_
  );_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
  if ($(this).is(':checked')) {_x000D_
    $('[name=age]').attr('form', 'fake-form-id');_x000D_
  } else {_x000D_
    $('[name=age]').removeAttr('form');    _x000D_
  }_x000D_
  _x000D_
  $('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
  <input type="text" value="John" name="name">_x000D_
  <input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude">  _x000D_
  <input type="checkbox" value="exclude age" id="exclude">_x000D_
  exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:

<input form="fakeForm" type="text" readonly value="random value" />

Simple try to remove name attribute from input element.
So it has to look like

<input type="checkbox" checked="" id="class_box_2" value="2">

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to userscripts

Uncaught ReferenceError: function is not defined with onclick Manually adding a Userscript to Google Chrome Stop an input field in a form from being submitted