简体   繁体   中英

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.

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

and in javascript am checking like this:

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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