April 10, 2012

jquery issue copying data from div to input text

Question by Irfan Mulic

I am working on inplace edit for a form.
I am having two divs one of them holds display elements and the other holds input form.

When you click edit data moves from display div to input form. I see the change when I use val(text), however when I serialize the form to json elements are old.

I need some help understanding what is the problem here?

Here is some code:

function editForm2(){
    $("#editLink").click(function() {
        if (this.text == 'Edit') {
            console.log('editing');
            $("#display div.edit").each(function(i) {
                var e = $("#input :input")[i];
                $(e).val($(this).text());
            });
            $("#display").hide();
            $("#input").show();
            $(this).text('Save');
        }
        else if (this.text =='Save') {
            // problem is here... When I serialize the form I got nothing ?!
            console.log('saving');
            console.log($("#form1 :input")); // old values

            var json_form = $('#form1').serializeObject();
            console.log(json_form); // old values?
            $(this).text('Edit');

            $("#display").show();
            $("#input").hide();
        }
    });

    console.log(this);
}

$(document).ready(function() {
    editForm2();
});​

here is html

<div class="editSection" id="display" >
    <div id="person_firstName" class="edit" width="200">
        Hello
    </div>
    <div id="person_lastName" class="edit">
        World
    </div>
</div>

<div class="editSectionEdit" id="input" >
    <form id="form1">
        <input name="person_firstName_in" type="text" class="edit" value="123" >
        <input name="person_lastName_in" type="text" class="edit" value="456" >
    </form>
</div><br/>

<div id="buttons">
    <a href="#" id="editLink">Edit</a>
    <a href="#" id="cancelLink">Cancel</a>
</div><br>

<pre id="result"></pre>

Answer by Starx

The problem was .serializeObject() which was reported as undefined by firebug.

Here is your solution

var json_form = $('#form1').serialize();

Check here

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!