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 send it using JavaScript, but I want to exclude the field dontSubmitThisField

from the request. Is there a way to do this without Ajax?

+3
javascript submit forms


source to share


5 answers


Just turn off the field.

Or 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 submit event:

$('#myForm').submit(function(){
    $('input[name="dontSubmitThisField"]').prop('disabled', true);
});

      

+4


source to share


Why would you collect information that you don't need?



Regardless, if you remove the field name, it will not POST

+3


source to share


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

+1


source to share


To submit the form using JavaScript, use myForm.submit();

To exclude this field, remove it. You can store the id if you need to reference the field for some reason. Or - you can just ignore the field altogether on the server side.

+1


source to share


Disabled fields or fields without an attribute name

will not be sent.

However, if you want to name your fields and don't want to disable them, you can intercept all forms and disable all fields with the attribute data-no-submit

.

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

      

Then you can simply do:

<input type="text" name="dontSubmitThisField" data-no-submit>

      

+1


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics