如何使用JavaScript检查“组”中的特定无线电盒

时间:2012-03-01 18:41:41

标签: javascript html

我有一个收音机组,我需要使用javascript选择一个给定的收音机盒,如下例所示,我必须检查值为D3的选项

<input type="radio" name="day" id="day" value="D1" />D1
<input type="radio" name="day" id="day" value="D2" />D2
<input type="radio" name="day" id="day" value="D3" />D3
<input type="radio" name="day" id="day" value="D4" />D4

如何检查第三个选项?

5 个答案:

答案 0 :(得分:2)

请务必将此广播组放在表单中,然后将theNameOfTheForm更改为您表单的名称。

<form name="theNameOfTheForm">
..
..
..
</form>

java脚本函数:

<script type="text/javascript">

function select_radio_value(theValue)
{
for (var i=0; i < document.theNameOfTheForm.day.length; i++)
   {
   if (document.theNameOfTheForm.day[i].value == theValue)
      {
         document.theNameOfTheForm.day[i].checked = true;
      }
   }
}
</script>

现在您可以将它用作任何事件的js函数。例如:

<input type='button' name='c3' value='Click Here to check the D3 radio' onClick="javascript:select_radio_value('D3')">

答案 1 :(得分:0)

通常,您使用document.getElementById('day')。val或jQuery('#day')。val()。也就是说,如果他们有不同的ID。如果他们共享id,我不确定你可以使用document.getElementById,因为它假设id不同,但也许

jQuery('#day')[3].val()

可以工作,因为jQuery实际上返回一个与criteia匹配的元素数组

答案 2 :(得分:0)

从每个复选框中删除唯一的ID。您应该只在页面上有一个唯一的ID

在JavaScript中,使用以下内容访问该组中的第三个复选框,并将其设置为checked

var inputs = document.getElementsByTagName('input');
inputs[2].setAttribute('checked', 'checked');

或者,您只需将checked=checked添加到HTML中即可。

答案 3 :(得分:0)

function selectRadio(toBeSelectedRadioIndex)
{
    var radioElements = document.getElementById('day');
    radioElements[toBeSelectedRadioIndex].checked = true;
}

在许多情况下,您需要为您的元素添加不同的ID名称。 然后,您可以为它们指定相同的名称,并使用getElementsByTagName。 代码看起来像......

function selectRadio(toBeSelectedRadioIndex)
{
    var radioElements = document.getElementsByTagName('day');
    radioElements[toBeSelectedRadioIndex].checked = true;
}

答案 4 :(得分:0)

我会给单选按钮指定不同的ID,然后执行以下操作:

d3.select("input#thirdRadio").property("checked", "true");