选择的单选按钮转到URL

时间:2014-02-12 15:17:23

标签: javascript html forms radio-button

我正在尝试使用所选单选按钮的值转到特定网址。目前我正在使用的Javascript是选择输入的第一个“id”而不是使用实际选择的值。

HTML

<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
         <input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
         <input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
         <input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
         <input type="submit" />    
</form>

的Javascript

<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>

3 个答案:

答案 0 :(得分:1)

你有多个相同的ID,这很糟糕! getElementById期望一个结果,并且通过获取具有该ID的第一个元素(忽略其他2,应该如此)来获得一个结果。在类似元素上使用class属性。

    <input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
     <input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
     <input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student

获取已选中的元素

var checkedElem = document.querySelector(".ns_license:checked");

如果querySelector无法解决问题:

var elems = document.getElementsByClassName("ns_license"),
    checkedIndex = 0;

for (var i = 0; i < elems.length; i++) {
    if (elems[i].checked)
        checkedIndex = i;
}

您当前检查的元素位于elems[checkedIndex]

答案 1 :(得分:0)

要更改元素的特定属性,可以使用

  

setAttribute()

javascript的功能。应该让它发挥作用。

答案 2 :(得分:0)

虽然querySelector适用于现代浏览器,但它不适用于IE&lt; = 7

如果需要,可以遍历radios by name,然后检查是否已选中该值。如果是则返回该值。这是使用getRadioValue()函数:

<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
         <input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
         <input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
         <input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
         <input type="submit" />    
</form>

<script type="text/javascript">
function changeActionURL() {
    var forma = document.getElementById('myForm');
    forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}

function getRadioValue(name){
    var rads = document.getElementsByName('ns_license');
    for(var x=0; x<rads.length;x++){
        if(rads[x].checked){
            return rads[x].value;
        }
    }
}
</script>