开发者

How to use Javascript to create a checked radioButton in IE?

I was trying to create a ch开发者_Python百科ecked radiobutton by using following code in IE7. But it doesn't work.

var x = document.createElement("input");
x.type="radio";
x.checked=true; //I also tried setAttribute here which doesn't work either.

var spn=document.createElement("span");
spn.appendChild(x);

document.body.appendChild(spn);

I found that I could put x.checked=true after appendChild statement to make it work. I also noticed that when I change "radio" to "checkbox", it can be checked without changing the order of statements.

I am really confused by these facts. Am I doing something wrong in the above code?

SOLUTION: Finally, I understand it's a IE bug. When appending the new radio button to its parent, the checked property will be cleared. So, I have to call "x.checked=true;" as the last statement.


It's a weird IE thing....you need to use innerHTML or IE's extended createElement because "expando" properties don't work right on radio buttons. http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html


var x = document.createElement("input");
x.setAttribute('defaultChecked', 'defaultChecked');
x.type="radio";


var spn=document.createElement("span");
spn.appendChild(x);

document.body.appendChild(spn);

This should do the trick.


This isn't jQuery : you gotta build the properties yourself:

var x = document.createElement("input");
x.type = 'radio';
x.checked = true;


But if it were jQuery:

$(document).ready(function() {
    var x = $("<input type='radio' checked='checked' value='value'/>");
    $("body").append($("<span></span>").append(x));});


var input = document.createElement("input");
input.setAttribute("type", "radio");
input.setAttribute("checked", "checked");

var span = document.createElement("span");
span.appendChild(input);

document.body.appendChild(span);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜