Delete selected key and value after it had been serialized to array by jQuery

Viewed 4770

I used serialize() jQuery function and it will catch all value by name of the selected form, like the code bellow.

$('#serialize').click(function(){
    var ser = $('#form1').serialize();
    alert(ser);
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <form id="form1">
    <input type="text" name="text1">
    <input type="text" name="text2">
    </form>
    <button id="serialize">Serialize</button>
  

Result

text1=&text2=

Is there a way to delete the text1 just after it serialize ?

The Result I expect

text2=
4 Answers

Rather than removing it after the fact, try to filter it before serializing it, for example:

$("#form1").find("input[name!=text1]").serialize();

This example will find find all of the inputs within form1 that doesn't have the name of text1, then it will serialize that.

An approach, that would let you have a data structure with the ignored form element names, would be this:

// Object with the names of the form elements to ignore
var filters = {
    "text1": true,
    "textN": true
};
$("#form1")
    .find(":input")
    .filter(function (i, item) {
        return !filters[item.name];
    })
    .serialize();

You can remove from serialize by making element to disabled

$('#serialize').click(function(){
    removeParam("#form1 [name=text1]");
    var ser = $('#form1').serialize();
    console.log(ser);
});

function removeParam(p) {
    $(p).attr("disabled",true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <form id="form1">
    <input type="text" name="text1">
    <input type="text" name="text2">
    </form>
    <button id="serialize">Serialize</button>

If you want to exclude multiple values as per your comment in the accepted answer Here is the solution that works best.

$("#form1:input[name!=text1][name!=text2]").serialize();
Related