简体   繁体   中英

How to serialize current div by using $(this).parent() with JQuery?

I am trying to serialize the current div by using a clickevent. See code for good explanation:

$("#createreview").live('click', function() {
    alert($(this).parent().serialize());
    $.post('/admin/home/review/create/', $(this).parent().serialize(), function(data){
       alert('Review succesfully added to database.' +data);
    });
});

Alert will show nothing, which means the div is not being serialized. This is the html in question. It's inside a dialog, which is also the reason why i have to use live().

<div id="reviewdiv">
            <input type="hidden" value="7" name="homeid">
            <label>Content</label><textarea name="reviewcontent" id="reviews" rows="3" cols="60"></textarea><br>
            <label>Author</label> <input type="text" name="reviewauthor"><button class="ui-state-default ui-corner-all" id="createreview">Save Review</button><button class="ui-state-default ui-corner-all" id="removereview">Remove Review</button><br>
        </div>

Also this code is working without a problem to remove the current div by using the clickevent and parent selector.

$("#removereview").live('click', function() {
  $(this).parent().slideUp();
});

You can serialize a <div> .

The serialize uses internally the param method. So to serialize input elements that do not belong to a form, use the param method. Example: http://jsfiddle.net/DdVqJ/

But remember, the correct (and semantic) way is to put your input elements inside a form.

You can't serialize a <div> , you need to have a <form> , so replace this:

<div id="reviewdiv">

With this:

<form id="reviewdiv">

Then you can use this to serialize:

$(this).closest('form').serialize()

To see the difference here's what you have (a <div> ) which doesn't serialize and here's the <form> version which does serialize. Because it uses the form.elements collection to loop through, nothing but a <form> works here.

我知道这是一个旧帖子,但你可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM