0

I am tring to create the update status box like facebook using Javascript/jQuery. When i click on post button the div element is created but the button that i have appended inside it is appearing only once.

This is my script code:

var hello = function() {
    var post = $.trim($("#status_message").val());

    if (post.length != 0) {
        $('<div id="hi">').text(post).prependTo('.posts');
        $("#status_message").val(" ");
        $("#hi").append($("#delete"));
        $("#hi").append($("#comment"));    
    }

}

html code:

<input type="button" id="post" name="submit" value="Post" class="btn btn-primary" onclick="hello()">  
<div class="counter"></div>  
CBroe
  • 91,630
  • 14
  • 92
  • 150
anonuser0428
  • 11,789
  • 22
  • 63
  • 86

1 Answers1

2

By using .append($('#delete')); You are simply moving an existing div called $('#delete') and appending it to the #hi element. So only one will be used...

However, some of the stuff you are doing doesn't make any sense anyways... You shouldn't use id if you are going to have more than one of them as a rule of thumb. If you have multiple elements with the same name you should have them identified as a part of a class and use the class attribute. If there is only one element then you should use id.

You would want to do something like this...

function hello() {
    var post = "test";
    var content = $('<div class="hi">');
    content.text(post)
        .append($('<div class="delete">delete</div>'))
        .append($('<div class="comment">comment</div>'))
        .prependTo('.posts');
}
honerlawd
  • 1,499
  • 11
  • 10
  • Hey that worked! I got the error that I had in my code. Thank you very much – anonuser0428 May 08 '15 at 17:33
  • If I have to delete just one ".hi" div. $("#delete").click(function() { $(this).remove(); }); is what comes in my mind. Is something wrong with it? – anonuser0428 May 08 '15 at 17:45
  • If you want to delete one using the delete class you would add an onclick to the delete and then do something along `$(this).closest('.hi').remove();` to remove the element. – honerlawd May 08 '15 at 17:46