13

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?

Victor2748
  • 4,149
  • 13
  • 52
  • 89

6 Answers6

11

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);
});
Kishan
  • 915
  • 6
  • 12
6

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>
plalx
  • 42,889
  • 6
  • 74
  • 90
3

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

SwaJime
  • 41
  • 5
  • Not my first choice for most cases, but pretty clever. This may be the right answer for someone. – Tom Jul 05 '21 at 20:05
2

Why would you collect information you don't need?

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

Graham T
  • 968
  • 9
  • 14
  • 2
    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. – plalx Oct 24 '14 at 19:33
1

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

Community
  • 1
  • 1
undefined
  • 2,051
  • 3
  • 26
  • 47
1

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.

Howard Renollet
  • 4,609
  • 1
  • 24
  • 31