Juliette Dupuis
Juliette Dupuis

Reputation: 1037

Add an html element on click

I have a very simple function to render the value of an input "text" into the html.

<form>
    <input type="text" class='test'><input type='submit' value='send'>
</form>
<div class='test2'> </div>

<script>   
    $("form").submit(function() {
        var value = $('.test').val();
        $('.test2').html(value);
    });
</script>

The thing is that everytime we press "send", the new value replace the old one. I would like to display the new message without deleting the old ones, on top of them. i.e I would like to add a 'DIV' or a 'P' each time I click on the button send.

Thank you for your help.

Upvotes: 2

Views: 82

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

jsBin demo

$("form").submit(function(e) { 
  e.preventDefault();
  $('<div>',{ text: $('.test').val() }).appendTo('.test2');
  $('form').get(0).reset();
});

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47687

Try it like this

$("form").submit(function() {
    var value = $('.test').val();
    $('.test2').append('<p>' + value + '</p>');
});

Upvotes: 4

Related Questions