2013-04-10 111 views
0

下面的函数总是返回false,我想我知道为什么,但不知道如何解决它。它验证的无线电形式是使用循环生成的,我将每个无线电字段的ID设置为“myfilling”,我认为这就是我出错的地方。JS函数总是返回False

功能是:

if(!document.getElementById('myfilling').checked) { 
    var resultloc=document.getElementById("fillingerror"); 
    resultloc.innerHTML = "<span style='color:red;'>Please select a filling!<span>"; 
    return false; 
} else { 
    var resultloc=document.getElementById("fillingerror"); 
    resultloc.innerHTML = ""; 
    return true; 
} 

如果我选择在该领域的第一个单选按钮,没有错误。但是,如果我选择其他任何按钮,则会出现错误。我该如何解决?

无线电场与以下产生:

function make_filling_radio($filling) 
{ 
    $filling = array("Carne de Casa (shredded beef)", "Carnitas (shredded pork)", "Pulled BBQ Chicken", "Roasted Chili Lime Chicken", "Roasted Veggies"); 

    foreach ($filling as $value){ 
     if (!empty($filling) and (FALSE !== array_search($value, $filling))) 
      echo "<input type=\"radio\" name=\"filling\" value=\"$value\" id='myfilling'> $value<br>\n"; 
     else 
      echo "<input type=\"radio\" name=\"filling\" value=\"$value\" id='myfilling'> $value<br>\n"; 
    } 
} 
+0

向我们展示如何生成它以及相关标记。 – Gabe 2013-04-10 19:48:19

+2

_and我设置每个无线电字段的ID为“myfilling”_ - id必须是**唯一的** – Andreas 2013-04-10 19:49:23

+0

我意识到它们必须是唯一的,但我该如何解决这个问题?用于生成无线电领域的代码包括 – 2013-04-10 19:59:13

回答

0

要使用纯JS解决这个问题,你可以通过所有input标签与getElementsByName环(而不是使用getElementById,因为你的ID不是唯一的) :

var input_elements = document.getElementsByName("filling"); 

for (var i=0; i < input_elements.length; i++) { 
    if (elements[i].checked) { 
    //checked radio found 
    return true; 
    } 
} 

//... 
return false;