Excluding certain inputs on serialize

前端 未结 6 1112
长发绾君心
长发绾君心 2020-12-29 20:05

I am trying to exclude an input by name (it is a hidden input holding my nonce)

The following question is almost what I am looking for:

How do I use jQuery&#

相关标签:
6条回答
  • 2020-12-29 20:20

    I am not happy with 'input[name!=security]' because it exclude all other input type like select,.. You can add them manually but this list just keep increasing with new HTML tags. So with every new tag coming, your code is broken again.

    Here is my solution:

    $form.find(':not(input[name=draft])').serialize()
    

    or

    $('form[name=expenses] :not(input[name=draft])').serialize()
    

    Space is very important in second example.

    0 讨论(0)
  • 2020-12-29 20:25

    You can filter result array

    var ignoreFields = ["_csrf"];
    
    $('form')
     .serializeArray()
     .filter(function(val){
        return ignoreFields.indexOf(val.name) === -1;
     });
    

    Or shorter variant

    $('form').serializeArray().filter(val => ignoreFields.indexOf(val.name) === -1)
    
    0 讨论(0)
  • 2020-12-29 20:26

    In my situation, this worked fine:

    $("fieldset").not(".tasks-container").serialize()
    
    0 讨论(0)
  • 2020-12-29 20:28

    First, you need to invoke the .find() method like:

    var serializedReturn = $(this).find('input[name!=security]').serialize(); 
    

    Otherwise the complete string would go into the css query engine (Sizzle).

    Secondly:

    I have another form with the id of ofform-reset and if i use:

    You need to change this. It's invalid markup to have multiple ID's. If I understood you wrong here, the first solution might also help you here, invoking the .find() method aswell:

    var serializedReturn = $('#ofform').find('input[name!=security]').serialize(); 
    
    0 讨论(0)
  • 2020-12-29 20:32

    You don't need the :, because input is an element not a pseudo selector. Secondly you cannot use an object and a text string like that in your selector. You instead need to supply this as the scope argument to $():

    $('#ofform').live('submit', function(e) {
        e.preventDefault();
        var serializedReturn = $('input[name!=security]', this).serialize();        
    });
    
    0 讨论(0)
  • 2020-12-29 20:40

    Solved ! You should use the given solution to exclude input field to be serialized. It's tested and solved my problem.

    var formdata = $($("#myform")[0].elements).not("#field_id").serialize();
    

    for multiple fields, you can use the class name to exclude them.

    var formdata = $($("#myform")[0].elements).not(".class_name").serialize();
    
    0 讨论(0)
提交回复
热议问题