150

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.

Acorn
  • 49,061
  • 27
  • 133
  • 172
  • 2
    what's the problem if they get submitted? You can choose which fields to process in server-side language. – Sarfraz Jun 09 '10 at 17:01
  • 7
    I don't believe un-named form elements show up when a form is submitted - if you can write your JS to refer to them by ID you could leave their names empty, effectively preventing them from submitting. – g.d.d.c Jun 09 '10 at 17:02
  • 4
    leave the name attribute field blank – deostroll Jun 09 '10 at 17:03
  • @Sarfraz Ahmed: I'm writing a greasemonkey script, so I have no control over the website. – Acorn Jun 09 '10 at 17:06
  • 12
    According to the w3: To be included in a form's submission. a field (form element) must be defined within the form element, and must have a name attribute. Elements without names, or not contained in the form, are not submitted to the server. – kennebec Jun 09 '10 at 17:40
  • @kennebec: Thanks, this answers a question I had elsewhere. Nice to know that omitting the name is actually part of the standard and not just a common implementation quirk. – BlairHippo Jun 09 '10 at 17:47
  • Sadly, if you use javascript to remove the name element on a submit event, it seems to still get included in the submission by IE :( – Jon Marnock Mar 20 '13 at 07:06
  • @kennebec, [What about the order](http://stackoverflow.com/questions/1944019/how-do-i-get-all-checkbox-variables-even-if-not-checked-from-html-to-php/1944065#comment44668453_1944065) when there are elements that share the **same** name? – Pacerier Jan 27 '15 at 05:49

14 Answers14

194

You could insert input fields without "name" attribute:

<input type="text" id="in-between" />

Or you could simply remove them once the form is submitted (in jQuery):

$("form").submit(function() {
   $(this).children('#in-between').remove();
});
Chris van Chip
  • 504
  • 4
  • 20
Gal
  • 23,122
  • 32
  • 97
  • 118
  • 9
    Omitting the name prevents it from being submitted? Cool, I didn't know that. Does this work on all browsers? Is it part of a standard, or is it an implementation quirk? – BlairHippo Jun 09 '10 at 17:12
  • If input elements with no name attribute don't get submitted then this is an amazingly simple perfect solution! Is this cross browser compatible? Can anyone confirm? – Acorn Jun 09 '10 at 17:14
  • 2
    @Acorn I'm not entirely sure, but it's worth reading about. Essentially if you omit the "name" attribute value you can't access that value through any method... so it could be that the value is simply discarded by the browser. If it's pivotal to be safe for you, go for the jquery/javascript option (just note that the fields WILL be submitted when javascript is easily disabled -- so don't rely any of your security mechanisms on it). – Gal Jun 09 '10 at 17:23
  • 18
    I tested leaving out the name attribute with chrome, firefox, safari and it seems that the form fields are being submitted to the server with an empty string for the name. I inspected the post data using WebScarab and found that the data is being sent. For now I guess I will have to disable the fields to prevent them from being submitted. – kldavis4 Aug 07 '12 at 16:26
  • 1
    @kldavis4 - it seems that both stripe (stripe.js) and Braintree (braintree.js) [link]https://www.braintreepayments.com/docs/python/guide/getting_paid use the "leaving out the name" attribute concept to stop data hitting the servers thus reducing need for "PCI" compliance... if you say that the "data" is being sent are they in error? – Rahul Dighe Mar 11 '13 at 17:31
  • 1
    @Rahul Based on my testing, it would seem so. It's been a while since I looked at this. It is possible there was some quirk with JSF or Richfaces (which I was using for the form), but it should be pretty simple to verify using a proxy (like WebScarab) and a test html form. – kldavis4 Mar 11 '13 at 20:45
  • @Rahul Even based on tests, I'd hesitate to say that they are in _error_. Removing the `name` property is a simple and effective way to have a field ignored, since it can be easily discarded by the server, possibly without even effort from the dev. If all they are trying to do is _ignore_ the data, then **it's perfectly fine to do this**. Of course, if there are _security_ repercussions that they are failing to mitigate, then I agree that they are in error. Though even then, as long as the connection is encrypted, many security concerns are merely academic. – JMTyler Mar 15 '13 at 14:52
  • 4
    [does form data still transfer if the input tag has no name?](http://stackoverflow.com/questions/12543848/does-form-data-still-transfer-if-the-input-tag-has-no-name) – Kevin Wheeler Jun 12 '16 at 00:08
  • Note about IE10/11 - ( just in case you need to deal with them). IE11 still sends empty fields via GET-method forms - you will get this in your URL: `/some_path?=&=&=&=&` (note the empty values). I've set `name` to empty in JS – Alex from Jitbit Oct 03 '17 at 23:19
  • As of 2017, both IE11 & Edge send form fields with the name property being removed via JS. I had to remove the value of the form field as well to prevent it entirely. – jaywilliams Nov 10 '17 at 16:39
  • You got `/some_path?=&=&=&=&` because you left the name attribute on the input with an empty value, instead of removing the attribute entirely. Those are two different things in HTML. – user2867288 Feb 12 '19 at 14:48
  • If i have to toggle between 'removeING' and adding it back, how do i do that? – Toni Aug 07 '19 at 15:37
  • I found removing the name doesn't stop `enter` submitting the form (chrome). – scipilot May 14 '20 at 04:10
  • Some types of inputs (e.g. `radio`) don't work properly without the `name` attribute. – Sasha Oct 14 '20 at 11:31
  • simple is best, thanks! – John Contarino Jan 14 '22 at 17:03
  • @kldavis4 What you said is so important, I was processing a large input file field to compress it so the request wasn't too large, but it was still! Now I know why. – Carlos López Marí Feb 15 '23 at 12:48
  • **Data point:** Tested removing name attribute. **Context:** Firefox, `
    `. **Result:** input dissapears from the Request in the Developer Tool's Network Tab
    – Madacol Jun 29 '23 at 10:17
69

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.

Johrn
  • 1,390
  • 7
  • 8
  • The idea is for my inserted fields to be usable so that the user can change checkboxes etc. and then submit them to my javascript. – Acorn Jun 09 '10 at 17:05
  • 4
    Disabled could still work, if you only disable the fields onsubmit or based on a checkbox being selected. That way you're not just throwing away the `name` property, which you might want to hold onto if you want it to be used later. – JMTyler Mar 15 '13 at 14:55
  • This is great when you have to submit the form using AJAX and don't want to remove your inputs from the form or remove their `name` attribute. – Nolonar Aug 12 '14 at 12:12
  • adding disabled will not allow the select fields to be selectable. – imshashi17 Apr 12 '21 at 20:35
29

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">
Lesha Pipiev
  • 3,251
  • 4
  • 31
  • 65
23

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" />
farvgnugn
  • 231
  • 2
  • 4
  • 2
    while this probably works (haven't tested), unless you actually define `fakeForm` elsewhere (no need to submit) this results in invalid HTML. – Brian H. May 11 '17 at 10:22
  • 2
    If you don't want to add javascript and you need the input inside the form with user interaction. This is by far the most simple solution from my perspective. – yannisalexiou Oct 29 '17 at 20:11
  • 1
    NOTE : This solution **doesn't work with IE**. Check [here](https://caniuse.com/#feat=form-attribute) – Harvey Jun 14 '19 at 11:10
  • 2
    Looks like `form=""` is enough to exclude fields from being submitted. Tested in Firefox 102 and Brave with Chromium 103, I'm not an Apple prisoner (no Safari here). And who cares about deprecated dinosaurs like the IE anymore... – ygoe Jul 17 '22 at 11:09
  • Best and simple solution when generates inputs by javascript with its own logic inside any page where container is wrapped into tag
    – realmag777 Oct 17 '22 at 12:41
12

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;
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
5

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...

Delfshkrimm
  • 59
  • 1
  • 2
  • 1
    Interesting observation but have you tested this in various browsers? I wonder if it is by design, by specification or just a quirk of browser behaviour. Will it be a reliable method into the future as browsers change? – scipilot May 14 '20 at 04:05
  • 1
    According to the documentation on MDN, `
    ` elements are not supposed to contain other `
    ` elements, so I suspect this behavior indeed depends a bit on the browser.
    – LarsW Oct 28 '21 at 14:09
4

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.

Will
  • 301
  • 1
  • 7
  • 18
4

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');

Pikka pikka
  • 118
  • 7
2

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.

ring bearer
  • 20,383
  • 7
  • 59
  • 72
0

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.

BlairHippo
  • 9,502
  • 10
  • 54
  • 78
0
$('#serialize').click(function () {
  $('#out').text(
    $('form').serialize()
  );
});

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

<input type="button" value="serialize" id="serialize">
<label for="exclude">  
  <input type="checkbox" value="exclude age" id="exclude">
  exlude age
</label>

<pre id="out"></pre>
0

wrap inputs that you want not to submit with <fieldset disabled>

<form action="/">
<fieldset disabled>
  <input type="text" value="John" name="name">
  <input type="number" value="100" name="age">
</fieldset>
</form>
Adam Pery
  • 1,924
  • 22
  • 21
0

Another option is you can disassociate the input to the form by associating it to another form name. Eg. add form='none' to indicate that the input belongs to a form named 'none' (which in this case, there is no form with that name). This is a little hacky, but it works.

<input form='none' name='name' value='John' type='textbox' />
LydiaHendriks
  • 1,290
  • 2
  • 11
  • 19
-2

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 :)