Making jquery checkbox - cannot set checked value

it seems simple enough, I donโ€™t know if this is a mistake or just something I am doing wrong.

What I want to do is create a checkbox in jquery and then return the input line. I have this code:

var obj = $('<input>'); obj.attr('disabled', 'disabled'); obj.attr('type', 'checkbox'); obj.attr('checked', 'checked'); // this does not work! 

no matter how i try to execute this obj, the attribute 'checked' is never output.

So I tried:

 $('<div>').append(obj).remove().html(); 

and it returns:

 <input type="checkbox" disabled="disabled" /> 

I tried to set the id attribute, it does not matter. I also tried this, but it does not work:

 obj.attr('checked', true); 

Any suggestions on how to get an input tag processed using a verified attribute set to "checked" (via jquery)?

I understand that I can just do this by concatenating strings, but now I really want to know why it doesn't work as it should.

EDIT

You can try this for yourself in firebug. Create an obj object both my way and cletus , then try making it a string. You will find that the "checked" attribute will never be displayed.

+3
jquery checkbox
source share
4 answers

You are right, there is some strange thing with the attribute "checked". It seems to take effect only after it is actually displayed by the browser. (And not just in the fragment.)

For example, using your code,

 var obj = $('<input />'); obj.attr('disabled', 'disabled'); obj.attr('type', 'checkbox'); obj.attr('checked', 'checked'); var wrapper = $('<div />').append(obj); alert(wrapper.html()); // notice, no checked attr in this string... $('body').prepend(obj); // but now notice, it IS checked when it drawn! 

I know that this is not an โ€œanswerโ€ as such, but I wanted to inform you that you are not going crazy. I would also be interested to know why this is so.

Good luck

+2
source share

This works for me:

 $("<input>").attr({ type: "checkbox", disabled: true, checked: true }).appendTo("body"); 

Tested in FF 3.6, Chrome 4 and IE 8 (compat).

+3
source share

Have you tried just

 obj.attr('checked'); 

Not trying to be despicable. Just sincerely wanted to know if he had done anything for him.

I think you're right. I never thought about this because jQuery has a built-in workaround in the :checked selector, so it was never a problem.

0
source share

The only way I know this will allow you to return the entire HTML object, as the string will use the outerHTML trick:

 jQuery.fn.outerHTML = function () { return $('<div>').append(this.eq(0).clone()).html(); }; 

Then just

 $("<input>").attr({ type: "checkbox", disabled: true, checked: true }).outerHTML(); 

Gives you the full line.

0
source share

All Articles