2017-07-04 58 views
-1

我想創建一個單選按鈕使用JavaScript。但它似乎沒有工作我想創建一個javascript DOM單選按鈕和屬性動態

function div() 
{ 
    var newDiv = document.createElement("div"); 

    newDiv.id = "myDiv"; 
    newDiv.style.width = "200px"; 
    newDiv.style.height = "100px"; 
    newDiv.style.background = "red"; 
    newDiv.style.border = "inset"; 
    newDiv.style.borderwidth = "20px"; 
    newDiv.style.borderColor = "blue"; 

    document.body.appendChild(newDiv); 
} 
+0

歡迎SO。請閱讀:** [如何提出一個好問題](https://stackoverflow.com/help/how-to-ask)**。在這種情況下:你的問題是什麼? – KoenV

+0

我需要編碼爲javascript單選按鈕來創建組件 – ahmed

回答

2

更改divinput。而添加type="radio"

function div() { 
 
    var newDiv = document.createElement("input"); 
 
    newDiv.id = "myDiv"; 
 
    newDiv.style.width = "200px"; 
 
    newDiv.style.height = "100px"; 
 
    newDiv.style.background = "red"; 
 
    newDiv.style.border = "inset"; 
 
    newDiv.style.borderwidth = "20px"; 
 
    newDiv.style.borderColor = "blue"; 
 
    newDiv.type="radio"; 
 
    document.body.appendChild(newDiv); 
 
} 
 
div();

更新

如何動態設置屬性? 與上面相同。 Dom element call via id

function div() { 
 
    // var newDiv = document.getElementById("input"); //its call the element 
 
    //or 
 
    var newDiv = document.getElementsByTagName("input")[0]; 
 
    newDiv.id = "myDiv"; 
 
     newDiv.style.width = "200px"; 
 
     newDiv.style.height = "100px"; 
 
     newDiv.style.background = "red"; 
 
     newDiv.style.border = "inset"; 
 
     newDiv.style.borderwidth = "20px"; 
 
     newDiv.style.borderColor = "blue"; 
 
     newDiv.type="radio"; 
 
     document.body.appendChild(newDiv); 
 
     console.log(newDiv.outerHTML) 
 
    } 
 
    div();
<input id="input">

+0

沒有兄弟我想問的是如何動態設置屬性? – ahmed

+0

@ahmed。像上面一樣。你需要調用元素而不是create.see我更新的一個 – prasanth

+0

newDiv.id =「動態改變這裏」; @ prasad13 – ahmed