简体   繁体   中英

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. ie I would like to add a 'DIV' or a 'P' each time I click on the button send.

Thank you for your help.

Try it like this

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

jsBin demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM