简体   繁体   English

struts2单选按钮id属性值正在动态更改

[英]struts2 radio button id attribute value is changing dynamically

I have a javscript function where I need to check whether any of radio buttons are checked or not. 我有一个脚本功能,需要检查是否选中了任何单选按钮。 I am doing with id attribute. 我正在使用id属性。

<s:radio id="gender" name="bean.gender" list="#{'male':'male','female':'female'}"/>

and in javascript am checking like this: 并在javascript中进行如下检查:

if (radVal(document.forms[0].gender) == "") {
    alert("enter gender");
    document.forms[0].gender[0].focus();
    return false;
}

function radVal(radName) {
    var radioVal = "";
    for (var i = 0; i < radName.length; i++) {
        if (radName[i].checked) {
            radioVal = radName[i].value;
        }
    }
    return radioVal;
}

and in runtime am seeing the id as 'gendermale' and 'genderfemale', so am unable to get the proper id. 并且在运行时将ID视为“ gendermale”和“ genderfemale”,因此无法获取正确的ID。

Since every id in a page must be unique, and the <s:radio> tag is generating multiple HTML tags, it is generating multiple id s; 由于页面中的每个id都必须唯一,并且<s:radio>标记正在生成多个HTML标记,因此它会生成多个id ;因此,

the real mistake however is that you are looping through radio buttons like if they would be checkboxes, while they're not. 但是,真正的错误是,您正在单选按钮之间进行循环浏览,就像它们是否是复选框一样,而不是。

Radio buttons allows only one choice . 单选按钮仅允许选择一种

Take the element by name and read the value, to get the selected one, or empty if none is selected. 按名称获取元素并读取值,以获取所选元素;如果未选择任何元素,则为空。

Normally you could use dot notation ( . ) 通常您可以使用点符号.

document.forms[0].bean.gender.value

but since your name has a dot in it, you must use the other syntax ( [""] ): 但是由于您的名字中带有点,因此必须使用其他语法( [""] ):

document.forms[0]["bean.gender"].value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM