2013-04-27 102 views
0

嘿傢伙即時嘗試弄清楚如何確定哪個單選按鈕被選中使用只有JavaScript ...我知道這將是更容易使用一些jQuery,但我會認爲JavaScript的現在..我知道我可以通過名稱獲取元素的值(getElementsByName)並從那裏確定它。但不知何故它不工作....這裏是我的JS小提琴 http://jsfiddle.net/sean3200/LdNCT/而下面是我的代碼示例...謝謝!如何確定哪個單選按鈕被選中使用Javascript

var questions = { 

         allQuestions : [ 


        { 
         topQuestion:["Click on which producer produced Justins Timberlake 4th Album?", "What was the first disney movie Justin Timberlake firsr scored?", "What famous celebrity did Justin Timberlake dated ?", "Star Wars"], 
        },  
        { 
         question: "Select which movie did Justin Timberlake film score in 2008?", 
         choices:["Shark Tank", "The Incredibles", "Finding Memo", "Star Wars"], 
         correctAnswer:3 
        }, 
        { 

         question:"What city was Justin Timberlake born in?", 
         choices: ["Chicago", "Detroit", "Tenessee", "New York"], 
         correctAnswer:3 
        }, 
        { 

         question:"At the age of 11, what famous show did Justin Timberlake appeared on?", 
         choices: ["American Idol", "Family Fued", "Star Search", "The Voice"], 
         correctAnswer:3 
        }, 
        { 

         question:"What hit single did Justin Timberlake perform at the MTV Awards in 2002", 
         choices: ["Sexy Love", "Cry Me A River", "Like I Love You", "What Comes Around"], 
         correctAnswer:3 
        }, 
        { 

         question:"What boy band was Justin Timberlake apart of?", 
         choices: ["One Direction", "Black Street Boys", "98 Degrees", "NSync"], 
         correctAnswer:4 
        }  
         ] 
        }; 

        var newQues = Object.create(questions); 


        for (var i = 0; i < 4; i++){ 


        container = document.getElementById("container"); 
        list = document.getElementById("list"); 
        var li = document.createElement("input");  
        li.type = 'radio'; 
        li.name= 'radio_group';  
        li.id = 'id1'; 
        li.value = newQues.allQuestions[1].correctAnswer;       

        document.body.appendChild(li); 
        el = document.createElement("div"); 
        text = document.createTextNode(newQues.allQuestions[1].choices[i]) 
        list.appendChild(el); 
        el.appendChild(li); 
        el.appendChild(text);       

        } 


      var radios = document.getElementsByName("radio_group"); 
       for (var i = 0; i < radios.length; i++) { 
       if (radios[i].checked) {      
       alert(radios[i].value)       
        } 
       }; 
+0

會造成什麼樣的元素,從'EL =使用document.createElement(」 EL「)'? – RobG 2013-04-27 14:49:48

+0

@RobG - el元素包含輸入元素(li),然後將其附加到文檔主體。 - >>> el.appendChild(il) – 2013-04-27 14:54:47

+0

對不起,我當時是傻傻的。 * createElement *的參數應該是一個標籤名稱,「el」不是HTML文檔中的有效標籤名稱。 – RobG 2013-04-27 14:56:32

回答

0

演示:http://jsfiddle.net/LdNCT/2/

你沒有事件監聽你的單選按鈕,我添加了一個現在的工作

radios[i].addEventListener('change', function() { 
    alert(this.value); 
}); 
+0

非常感謝@ XCritics !!! – 2013-04-27 20:13:03

相關問題