Aaron Aaron - 2 months ago 8
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');



$message.submit(function(e){
console.log("Test");
});


$(document.body).on('click','.button', function(e) {
console.log($(this).val());
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' />");
$input.append('</form>');

$input.appendTo($("#contentWrap"));
});


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){
console.log("Test")
});


$(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

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">
</p>

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) {
  console.log($(this).val());
  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").append($input);
});

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

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

Comments