简体   繁体   中英

Append <li class> to <ul class> with jQuery

When I run the function in the browser, "[object Object]" shows up instead of the text stored inside the variable $new_comment. I wish to append user inputs.

HTML :

<li class="list-group-item">"User comments"</li>

<div class="comments">
    <ul class="list-group"></ul>
</div>

Js :

var addCommentFromInputBox = function() {
    var $new_comment;

    if ($(".input-group input").val() !== "") {
        $new_comment = $("<p>").text($(".input-group input").val());
        $new_comment.hide();

        $(".list-group").append('<li class="list-group-item">' + ($new_comment) + '</li>');
        $new_comment.fadeIn();
        $(".input-group input").val("");
    }
};

Everything runs fine when I change the code to:

$(".list-group").append($new_comment);

But I wish to style it with Bootstrap.

You can use it something like this $(".list-group").append($('<li class="list-group-item"></li>').html($new_comment));

Here this the full demo code

 addCommentFromInputBox = function() { var $new_comment; if ($(".input-group input").val() !== "") { $new_comment = $("<p>").text($(".input-group input").val()); $new_comment.hide(); $(".list-group").append($('<li class="list-group-item"></li>').html($new_comment)); $new_comment.fadeIn(); $(".input-group input").val(""); } } addCommentFromInputBox();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="comments"> <ul class="list-group"> </ul> </div>

var listGroupItem = $('<li class="list-group-item"></li>').html($new_comment)
$(".list-group").append($listGroupItem);

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