-1

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/

Aaron
  • 3,790
  • 11
  • 69
  • 121

2 Answers2

1

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">
Barmar
  • 596,455
  • 48
  • 393
  • 495
-1

Try this

$('#contentWrap').on('click', '.button', function(e) { 
    console.log($(this).val());   `
Chris Forrence
  • 9,648
  • 11
  • 43
  • 59
Reuben Gomes
  • 866
  • 8
  • 13