jQuery to serialize only elements within a div

后端 未结 8 1641
猫巷女王i
猫巷女王i 2020-11-28 20:52

I would like to get the same effect as jQuery.serialize() but I would like to return only the child elments of a given div.

Sample

相关标签:
8条回答
  • 2020-11-28 21:18

    No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

    $('#divId :input').serialize();
    

    Check https://jsbin.com/xabureladi/1 for a demonstration (https://jsbin.com/xabureladi/1/edit for the code)

    0 讨论(0)
  • 2020-11-28 21:18

    Try also this:

    $('#divId').find('input').serialize()

    0 讨论(0)
  • 2020-11-28 21:20

    You can improve the speed of your code if you restrict the items jQuery will look at.

    Use the selector :input instead of * to achieve it.

    $('#divId :input').serialize()
    

    This will make your code faster because the list of items is shorter.

    0 讨论(0)
  • 2020-11-28 21:20

    The function I use currently:

    /**
     * Serializes form or any other element with jQuery.serialize
     * @param el
     */
    serialize: function(el) {
        var serialized = $(el).serialize();
        if (!serialized) // not a form
            serialized = $(el).
              find('input[name],select[name],textarea[name]').serialize();
        return serialized;
    }
    
    0 讨论(0)
  • 2020-11-28 21:26
    $('#divId > input, #divId > select, #divId > textarea').serialize();
    
    0 讨论(0)
  • 2020-11-28 21:28

    serialize all the form-elements within a div.

    You could do that by targeting the div #target-div-id inside your form using :

    $('#target-div-id').find('select, textarea, input').serialize();
    
    0 讨论(0)
提交回复
热议问题