0

I am trying to convert form data upon submit to update a json object.

This is what I have so far:

var app = {
slidePreviews: "",
selectedTheme: "",
slideDuration: 7000,
    slides: []
};
$(document).ready(function() {

$('#slideForm').on('submit', function(event){
    var slide = $(this).toJSON;
    app.slides.push(slide);
    return false;
});
}); 
<div id="themeOption"></div> 
<div id="ppt"></div>

<pre><code id="presentation"></code></pre>

<form id="slideForm">
<dl>
    <dt><label for="presTitle">Title of the Presentation:</label></dt>
    <dd><input id="presTitle" type="text" name="presentation.title"/></dd>
</dl>
<dl>
    <dt><label for="slideTitle">Slide Title:</label></dt>
    <dd><input id="slideTitle" type="text" name="presentation.slide.title"/></dd>
</dl>
<dl>
    <dt><label for="slideHeader">Slide Header:</label></dt>
    <dd><input id="slideHeader" type="text" name="presentation.slide.header"/></dd>
</dl>
<dl>
    <dt>Content</dt>
    <dd>
        <textarea rows="5" cols="20" name="presentation.slide.content">Slide content here</textarea>
    </dd>
</dl>
<dl>
    <dt></dt>
    <dd><input type="submit" value="Send" /></dd>
</dl>

I want the object app to be updated with the form data. When I log "slide", I get "undefined". Any suggestions.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
swaggyP
  • 355
  • 1
  • 5
  • 18

3 Answers3

0

I think you need to add parens to your call to toJSON() call:

var slide = $(this).toJSON();
PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
0

Use the serialize function to serialize your form as JSON instead of the toJSON function, like this:

$(this).serialize();
clav
  • 4,221
  • 30
  • 43
  • when I log slides, it returns "function()". I don't seem to get any json – swaggyP Apr 11 '13 at 22:11
  • I don't see a close tag on your `
    ` tag. Is that just a typo?
    – clav Apr 11 '13 at 23:05
  • If it's printing "function()" when you print `slide` to the console, I'm guessing you forgot the parenthesis on the `serialize()` call, $(this).serialize without parenthesis would return the serialize function instead of calling it. Also, `serialize()` creates a string, you can use `serializeArray()` to get an array of name/value pairs, if you need a JSON object see [this question] (http://stackoverflow.com/a/1186309/1970746). – clav Apr 12 '13 at 02:23
0

You can use jQuery's serialize() like this:

var obj = $("#slideForm").serialize();
Travis J
  • 81,153
  • 41
  • 202
  • 273