JavaScript submit form excluding fields
Asked Answered
P

6

14

I have a simple html form:

<form action="test" method="post" id="myForm">
    <input type="text" name="myTextField">
    <input type="text" name="myTextField2">
    <input type="text" name="dontSubmitThisField">
</form>

And I need to submit it with JavaScript, but I want to exclude the dontSubmitThisField field from the request. Is there a way of doing that without Ajax?

Profuse answered 24/10, 2014 at 19:10 Comment(1)
The disabled html attribute will do what you wantArianaariane
F
12

Just disable the field.

Either do it via HTML if the field cannot be updated by the user: http://www.w3schools.com/tags/att_input_disabled.asp

Or do it via jQuery with a on submit event:

$('#myForm').submit(function(){
    $('input[name="dontSubmitThisField"]').prop('disabled', true);
});
Flatulent answered 24/10, 2014 at 19:21 Comment(0)
C
7

Disabled fields or fields without a name attribute won't submit.

However, if somehow you want to name your fields and do not want to disable them upfront, you could intercept all form submissions and disable every fields that have a data-no-submit attribute.

document.addEventListener('submit', function (e) {
    if (!e.defaultPrevented) {
        [].forEach.call(e.target.querySelectorAll('[data-no-submit]'), function (field) {
            field.disabled = true;
        });
    }
});

Then you can just do:

<input type="text" name="dontSubmitThisField" data-no-submit>
Cabotage answered 24/10, 2014 at 19:23 Comment(0)
V
3

Just add form="nosubmit" to the input. This assigns the field to a different form altogether, so it won't be submitted.

Vesture answered 5/7, 2021 at 11:34 Comment(1)
Not my first choice for most cases, but pretty clever. This may be the right answer for someone.Expurgatory
F
2

Why would you collect information you don't need?

Regardless, if you remove the field's name it won't POST

Flavescent answered 24/10, 2014 at 19:18 Comment(1)
It's not because you do not send the information to the server that you do not need to collect it. Think about a password change form. You would have a passwordConfirmation field which doesn't have to be sent.Cabotage
C
2

You can disable the field, and it won't be included in the post vars. Disabled form fields are not submitting data

Crazed answered 24/10, 2014 at 19:19 Comment(0)
A
2

To submit the form with JavaScript use myForm.submit(); To exclude the field, remove the name. You can keep an ID if you need to reference the field for some reason. Or - you can just ignore the field altogether on the server side.

Alpenhorn answered 24/10, 2014 at 19:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.