2

I've put a much simplified example on jsFiddle.

Basically, I'm trying to build up my HTML and then append the whole thing once I'm done. The JS looks like this:

var label = 'My label',
    var checkbox = $('<input type="checkbox">').prop({
                id: 'checkboxId',
                name: 'checkboxId',
                checked: visible
            });
    listItem = ('<li class="customise_option"><label>'+checkbox+' '+label+'</label></li>');

$('#mylist').append(checkbox);
$('#myotherlist').append(listItem);

Appending just checkbox is fine, but if I try to include checkbox within my listItem variable then I just get:

[object Object] My label

So, on it's own jQuery is fine with appending my checkbox as a string, but when I try to do anything with that it treats it as an object.

Having looked around there are some similar questions, but as I'm creating everything in JavaScript (rather than manipulating something that already exists in the DOM) it seems there must be a way to do what I want. Problem is I can't figure it out.

EDIT

I simplified my original example too much, not understanding the problem fully. I have updated the jsFiddle to show that on my checkbox I need to be able to add a bunch of properties. So, the checked property will be reliant on something else. As such, I need $ so I can access jQuery's prop function (I think).

Community
  • 1
  • 1
CherryFlavourPez
  • 7,529
  • 5
  • 45
  • 47

4 Answers4

2
var label = 'My label',
    checkbox = '<input type="checkbox">';
    listItem = '<li class="customise_option"><label>'+checkbox+' '+label+'</label></li>';

$('#mylist').append(checkbox);
$('#myotherlist').append(listItem);

Here's the jsfiddle. If you're adding HTML markup, all you need are strings; you weren't far away.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 1
    You should explain the jQuery object conflict so that he knows what went wrong and how to prevent it in future. – WizzHead Oct 24 '12 at 14:30
  • Well simply put, when you want to insert HTML, you insert strings. And then, once the HTML is on the page, you can use jQuery to access that HTML element. – frenchie Oct 24 '12 at 14:32
2

checkbox is a jquery object, when you say string + checkbox you're casting checkbox to a string (which gives [object Object]) and then appending it. you need to use append() there as well.

jbabey
  • 45,965
  • 12
  • 71
  • 94
0

Its because checkbox = $('<input type="checkbox">') returns a jquery object.

Either stick to jquery objects and use methods like text() etc, or stick to appending string representations of HTML. Just dont mix it.

Johan
  • 35,120
  • 54
  • 178
  • 293
0

This happens because the checkbox is an object. With this code, works

var label = 'My label', checkbox = '', listItem = ''+checkbox+' '+label+'';

$('#mylist').append(checkbox); $('#myotherlist').append(listItem);

manuerumx
  • 1,230
  • 14
  • 28