user1967599
user1967599

Reputation:

jquery getting form data

I am trying to create a submit form that shows after clicking on a div and then retreive the filled in form data. Below is a test that I'm playing with for a day now. The variable "term" is always printed as undefined. Could anybody help me with this?

$(document).ready(function () {
    $("#nexttable").on("click", "#addcomment", function () {
        document.getElementById("nexttable").innerHTML = "<form  action='maindatabase.php'   id='commentform' method='post'><textarea name='newcomment' placeholder='Start typing your comment... (required)' rows='5' cols='50' required></textarea><br />"
        + "<span id='sbutton'><input type='button' value='Submit'></span><input type='hidden'     name='inputtype' value='3'></form>";
    });
});

$(document).ready(function () {
    $("#nexttable").on("click", "#sbutton", function () {
        var $form = $(this);
        var term = $form.find("input[name='newcomment']").val();
        document.getElementById("nexttable").innerHTML = term;
    });
}); 

Upvotes: 0

Views: 2541

Answers (1)

OJay
OJay

Reputation: 4921

No input on the page with the name newcomment, its a textarea ie

$form.find( "input[name='newcomment']" ).val();

will not find anything, it should be

$form.find( "textarea[name='newcomment']" ).val();

There is also a problem with the this in the event handler, as it is a delegated event handler

    $(document).ready(function () {
        $("#nexttable").on("click", "#sbutton", function () {
            var $form = $(this); // <-- HERE, the this I do believe is in reference to the #sbutton element, not anyting to do with a form
            var term = $form.find("input[name='newcomment']").val();
            document.getElementById("nexttable").innerHTML = term;
        });
    });

I would change it to something more like

    $(document).ready(function () {
        $("#nexttable").on("click", "#sbutton", function () {
            var $form = $(this).parents('form'); // <-- HERE, actually get the form element, which will be a prent of this element clicked ont
            var term = $form.find("input[name='newcomment']").val();
            document.getElementById("nexttable").innerHTML = term;
        });
    });

Upvotes: 1

Related Questions