2016-04-27 5 views
1

Я чистил сеть за ответ на этот вопрос и не нашел ничего полезного. Я программирую викторину на одной веб-странице. У меня нет одной формы с несколькими группами переключателей, но с несколькими формами, каждая со своей группой переключателей.Несколько форм кнопок радиосвязи, одиночные группы, не могут извлекать значения

Каждый раз, когда я запускаю свой код для захвата значений из каждой формы, я получаю не более первой группы; после этого вторая итерация моего вызова функции говорит, что моя переменная для полей формы не определена.

Пример вызовов для формирования значения кода извлечения:

function submit_quiz(){ 
var one, two, three; 
one = getRadioValue(document.getElementById("ans1"), "a1"); 
alert(one); 
one = getRadioValue(document.getElementById("ans2"), "a2"); 
alert(two); 
one = getRadioValue(document.getElementById("ans3"), "a3"); 
alert(three); 
} 
function getRadioValue(form, name){ 
var val; 
var i; 

var f = form; 
var n = name; 

radios = f.elements[n]; 
len = radios.length; 

for(i=0; i<len; i++){ 
    if(radios[i].checked){ 
    val = radios[i].value; 
    break; 
    } 
} 
return val; 
} 

Пример кода для форм и радиокнопок:

<ol class="quiz_question"> 
    <li id="q1"> 
    <p>According to Sun Tzu, the study of war is what to the state?</p> 
    <form class="answer_selections" id="ans1"> 
    <input name="a1" value="1" type="radio" />A useless endeavor to be avoided.<br /> 
    <input name="a1" value="2" type="radio" />Too costly to be of any practical use.<br /> 
    <input name="a1" value="3" type="radio" />A matter of life and death.<br /> 
    <input name="a1" value="4" type="radio" />Important to the state's wealth.<br /> 
    </form> 
    </li> 
    <li id="q2"> 
    <p>Sun Tzu says long wars have what effect?</p> 
    <form class="answer_selections" id="ans2"> 
    <input name="a2" value="1" type="radio" />Both the state's wealth, and the army's strength wane.<br /> 
    <input name="a2" value="2" type="radio" />Then enemy's strenght is steadily ground into nothing.<br /> 
    <input name="a2" value="3" type="radio" />Both sides will eventually choose a mutually agreable peace.<br /> 
    <input name="a2" value="4" type="radio" />There will be no effect as the war will become a stalemate.<br /> 
    </form> 
    </li> 
    <li id="q3"> 
    <p>If your army is five times as big as your enemies, what is your best course of action?</p> 
    <form class="answer_selections" id="ans3"> 
    <input name="a3" value="1" type="radio" />Attempt to surround and destroy the enemy's forces.<br /> 
    <input name="a3" value="2" type="radio" />Pull back, and wait for a better opportunity to attack.<br /> 
    <input name="a3" value="3" type="radio" />Split your forces in two, and send one to attack the enemy's rear.<br /> 
    <input name="a3" value="4" type="radio" />Attack immediatly, unless the enemy holds some other serious advantage.<br /> 
    </form> 
    </li> 
+0

'два/three' объявлен как' undefined' и их значение не установлено в любом месте .. – Rayon

ответ

2

Не удалось найти кнопку, чтобы представить тест. Поэтому нужно добавить кнопку и приложить к ней слушателя onclick.

Также нет необходимости передавать форму id, так как имя переключателей отличается, document.getElementsByName может использоваться для получения кнопки с этим именем. Затем перейдите по списку узлов, чтобы найти отмеченную кнопку.

Также в функции submit_quiz вы сообщаете переменную two & three, но на самом деле они не определены.

var one, two, three; //Declared variable 
one = getRadioValue(document.getElementById("ans1"), "a1"); // Assigned to one 
alert(one); 
//Assigned to one again but not two 
    one = getRadioValue(document.getElementById("ans2"), "a2"); 
    alert(two); // alerting two but two in unassinged 
    // Assigned to one again ,but alerting three 
    one = getRadioValue(document.getElementById("ans3"), "a3"); 
    alert(three); //three is unassigned 

document.getElementById("submitQuiz").onclick =function(){ 
submit_quiz(); 
} 

function submit_quiz(){ 
var one, two, three; 
one = getRadioValue("a1"); 
alert(one); 
two = getRadioValue("a2"); 
alert(two); 
three = getRadioValue("a3"); 
alert(three); 
} 



function getRadioValue(name){ 
var val ="" 
var _getCheckedRadio = document.getElementsByName(name); 
for(var i =0;i<_getCheckedRadio.length;i++){ 
if (_getCheckedRadio[i].checked){ 
    val = _getCheckedRadio[i].value; 
} 
} 
return val; 
} 

jsFiddle

+0

Видимо, я был более уставшим, чем я думал, когда я закодирован это. Это были просто простые ошибки, которые вы указали (неловко опускать их). Огромное спасибо. Теперь я могу все зафиксировать и включить вовремя. –