Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Text to checkbox control in JQuery

Tags:

jquery

I have the this checkbox I'm trying to create in JQuery

<input type="checkbox" id="someID">Hello World</input>

I thought this was the equivalent JQuery code:

var $ctrl = $('<input/>').attr({ type: 'checkbox', id: 'someID', text: 'Hello World'})

But, when I add the $ctrl to this div tag it seems to not include the 'Hello World' text.

$("#renderedControl").append($ctrl);

Any ideas what I'm missing?

like image 534
Jason Avatar asked Feb 24 '12 04:02

Jason


2 Answers

The correct markup for what you're trying to do is this:

<label><input type="checkbox" id="someID">Hello World</label>

Input elements cannot contain content (and only require a closing tag or self-closing in xhtml).

To create the above with jQuery try some variation on this:

var $ctrl = $('<label />').html('Hello world')
                          .prepend($('<input/>').attr({ type: 'checkbox', id: 'someID'}));

Demo: http://jsfiddle.net/bwxza/

like image 166
nnnnnn Avatar answered Sep 22 '22 00:09

nnnnnn


try this

 var $ctrl =  $(document.createElement("input")).attr({
                     id:    'topicFilter-'
                    ,name:  'test'
                    ,value: 'test'
                    ,text :'my testing'
                    ,type:  'checkbox'
                    ,checked:true
            })

var lbl =  '<label>Hello world</label>';


 $("#renderedControl").append($ctrl.after(lbl));

Hops its helps

like image 23
Jignesh Rajput Avatar answered Sep 21 '22 00:09

Jignesh Rajput