Reputation: 882
1. var checkbox_html = $("<input type='checkbox' name='' value='' class='attach'/>");
3. var span_html = $("<span class='style'>" + $(item).attr('value') + "</span>");
3. $("#disallowed_list").append('<li><label>' + checkbox_html + span_html + '</label></li>');
This results in
[object Object][object Object]
Why am I not getting the html elements here?
UPDATE:
I need to change the attribute of the name and value in the input checkbox too. So I have kept the $ in front of the checkbox_html value.
Like this,
$(checkbox_html).attr("name", $(item).attr('name'));
$(checkbox_html).attr("value", $(item).attr('value'));
Upvotes: 1
Views: 58
Reputation: 23816
Try this:
var checkbox_html = "<input type='checkbox' name='' value='' class='attach'/>";
var span_html = "<span class='style'>" + $(item).attr('value') + "</span>";
$("#disallowed_list").append('<li><label>' + checkbox_html + span_html + '</label></li>');
You are getting [object Object][object Object]
because of you are using $
which is creating object of HTML
If you want to set value also, you can do this:
var checkbox_html = "<input type='checkbox' name='"+$(item).attr('name')+"' value='"+$(item).val()+"' class='attach'/>";
The way @tilaprimera wanted
var checkbox_html = $("<input type='checkbox' name='' value='' class='attach'/>");
var span_html = $("<span class='style'>" + $(item).attr('value') + "</span>");
var li = $('<li></li>');
var label = $('<label></label>');
li.append(label);
label.append(checkbox_html);
label.append(span_html);
$("#disallowed_list").append(li);
$(checkbox_html).attr("name", $(item).attr('name'));
$(checkbox_html).attr("value", $(item).attr('value'));
Upvotes: 1
Reputation: 19740
The problem is that checkbox_html
and span_html
are jQuery objects. You can't just put them in the middle of a string and expect them to spit out HTML. In order to get the HTML, you can use the native outerHTML
.
$("#disallowed_list").append('<li><label>' + checkbox_html.get(0).outerHTML + span_html.get(0).outerHTML + '</label></li>');
Also, in your second example, I see you're using $(checkbox_html)
. You don't need to do this, because checkbox_html
is already a jQuery object. You can just do this:
checkbox_html.attr("name", $(item).attr('name'));
checkbox_html.attr("value", $(item).attr('value'));
This is why it's best practice to prefix jQuery objects with $, so you won't accidentally double-wrap the object (not that it will break anything, but it's just poor practice). For example:
var $checkbox_html = $("<input type='checkbox' name='' value='' class='attach'/>");
var $span_html = $("<span class='style'>" + $(item).attr('value') + "</span>");
Then use code like this to access those variables:
$checkbox_html.attr("name", $(item).attr('name'));
$checkbox_html.attr("value", $(item).attr('value'));
In this case, it's easy to see that $($checkbox_html)
would be incorrect without having to go and check the variable type.
Upvotes: 1