Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript submit form excluding fields

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?

like image 211
Victor2748 Avatar asked Oct 24 '14 19:10

Victor2748


People also ask

Are hidden fields submitted?

A hidden field lets web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.

How do you prevent a form from clearing fields on submit?

You can use preventDefault method of the event object. Show activity on this post. Alternatively, you could use event.

Which attribute prevents the data entered into a field from being submitted with the form?

The disabled Attribute The value of a disabled input field will not be sent when submitting the form!

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript.


3 Answers

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

like image 69
SwaJime Avatar answered Sep 26 '22 03:09

SwaJime


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);
});
like image 10
Kishan Avatar answered Oct 17 '22 10:10

Kishan


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>
like image 5
plalx Avatar answered Oct 17 '22 12:10

plalx