jQuery to serialize only elements within a div

后端 未结 8 1642
猫巷女王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:35

    If those elements have a common class name, one may also use this:

    $('#your_div .your_classname').serialize()
    

    This way you can avoid selection of buttons, which will be selected using the jQuery selector :input. Though this can also be avoided by using $('#your_div :input:not(:button)').serialize();

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

    What about my solution:

    function serializeDiv( $div, serialize_method )
    {
        // Accepts 'serialize', 'serializeArray'; Implicit 'serialize'
        serialize_method = serialize_method || 'serialize';
    
        // Unique selector for wrapper forms
        var inner_wrapper_class = 'any_unique_class_for_wrapped_content';
    
        // Wrap content with a form
        $div.wrapInner( "<form class='"+inner_wrapper_class+"'></form>" );
    
        // Serialize inputs
        var result = $('.'+inner_wrapper_class, $div)[serialize_method]();
    
        // Eliminate newly created form
        $('.script_wrap_inner_div_form', $div).contents().unwrap();
    
        // Return result
        return result;
    }
    
    /* USE: */
    
    // For: $('#div').serialize()
    serializeDiv($('#div')); /* or */ serializeDiv($('#div'), 'serialize');
    
    // For: $('#div').serializeArray()
    serializeDiv($('#div'), 'serializeArray');
    

    function serializeDiv( $div, serialize_method )
    {
    	// Accepts 'serialize', 'serializeArray'; Implicit 'serialize'
    	serialize_method = serialize_method || 'serialize';
    
    	// Unique selector for wrapper forms
    	var inner_wrapper_class = 'any_unique_class_for_wrapped_content';
    
    	// Wrap content with a form
    	$div.wrapInner( "<form class='"+inner_wrapper_class+"'></form>" );
    
    	// Serialize inputs
    	var result = $('.'+inner_wrapper_class, $div)[serialize_method]();
    
    	// Eliminate newly created form
    	$('.script_wrap_inner_div_form', $div).contents().unwrap();
    
    	// Return result
    	return result;
    }
    
    /* USE: */
    
    var r = serializeDiv($('#div')); /* or serializeDiv($('#div'), 'serialize'); */
    console.log("For: $('#div').serialize()");
    console.log(r);
    
    var r = serializeDiv($('#div'), 'serializeArray');
    console.log("For: $('#div').serializeArray()");
    console.log(r);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="div">
      <input name="input1" value="input1_value">
      <textarea name="textarea1">textarea_value</textarea>
    </div>

    0 讨论(0)
提交回复
热议问题