Aaron Aaron - 1 year ago 57
HTML Question

Submitting a dynamically created form in jQuery

I am trying to submit a form that I dynamically created. I am using the .submit, but it is not working. Here is my code

var $message = $('.message');


$(document.body).on('click','.button', function(e) {
var $input = '';
$input = $('<p>Chat with '+$(this).val()+'</p>');
$input.append('<div class = "chat" style="height:200px"></div>');
$input.append('<form class="message">');
$input.append('<input size = "35" class="messages">');
$input.append("<br><input type='submit' class='send_message' value = 'Send' />");


The code for document.body created the form. However, when I click the submit button nothing happens.

I also tried

$('#contentWrap').on("submit", ".message", function(e){

$(parent).on(event, child, function) is what most of the posts I read say to do. However, I must be doing something else wrong.

Here is the fill front end code in js fiddle https://jsfiddle.net/55Ln0wgu/

Answer Source

The problem is that the submit button isn't in the form. You're appending each <input> element to the <p>, not the <form>. The result is equivalent to this HTML, which has an empty <form>.

<p>Chat with 
    <div class="chat" style="height:200px"></div>
    <form class="message"></form>
    <input size="35" class="messages"><br>
    <input type="submit" class="send_message" value="Send">

Remember, .append() operates on the DOM hierarchy, it's not concatenating strings to the HTML.

Your code would work if you built $input as a string.

You also need to use event delegation for the Submit button, since it's being added dynamically.

$(document.body).on('click', '.button', function(e) {
  var $input = '<p>Chat with ' + $(this).val();
  $input += '<div class = "chat" style="height:200px"></div>';
  $input += '<form class="message">';
  $input += '<input size = "35" class="messages">';
  $input += "<br><input type='submit' class='send_message' value = 'Send' />";
  $input += '</form></p>';


$('#contentWrap').on("submit", ".message", function(e) {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Form should appear here:
<div id="contentWrap">

Chat with:
<input type="button" class="button" value="Fred">
<input type="button" class="button" value="Joe">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download