Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent form element from sending some fields we don't want?

I have a form element that contains about 5 fields which final query is going to create by processing values those fields. So I want to send only final query, not all of those, to the server. How can I exclude those fields from being submitted (using jQuery)?

<form action="abc/def.aspx" method="get">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="text" name="field3" />
    <input type="text" name="field4" />
    <input type="text" name="field5" />
    <input type="hidden" name="final" />
    <input type="submit" value="Send" />
</form>

Output of form submission looks like below:

abc/def.aspx?field1=val1&field2=val2&field3=val3&field4=val4&field5=val5&final=finalQuery
like image 371
Sadegh Avatar asked Jul 11 '10 14:07

Sadegh


2 Answers

Remove the name attribute on the fields you do not want submitted to the server.

<form action="abc/def.aspx" method="get">
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <input type="hidden" name="final" />
    <input type="submit" value="Send" />
</form>

This is the simplest way to achieve what you want, and it works on all major browsers.

W3 spec talks about only submitting form values when name is present: http://www.w3.org/TR/html401/interact/forms.html#h-17.2

like image 182
lmanners Avatar answered Oct 24 '22 06:10

lmanners


Remove the element on submit.

On the onsubmit handler:

$(formElement).submit(function() {
    $(this.field1).remove(); //removing field 1 from query
    return true; //send
});

Disabling the form element also stops it from being entered into the query.(tested on Chrome)

$(formElement).submit(function() {
    this.field1.disabled = true;
    return true; //send
});
like image 29
tcooc Avatar answered Oct 24 '22 07:10

tcooc