2

I'm making a page in JSP and am unable to determine how to do the following.

I have a bunch of radio buttons generated dynamically in a for loop

<%
for (Something something : somethings) {
    for (Random random : something.getRandoms ()) { %>
        <input type ="radio" name="<%= something%>" value="<%= random.toString()%>"><%= random%> <br>
<% }%>
    Some text here : <input type = "text" name="<%= something%>Text" placeholder="Some more text here"/>
<% }%>

What I want to do is:

When one of the radio buttons are checked, the text box should be made empty and when some text is entered in the text box, the radio buttons should be cleared.

I tried in javascript by saying <name of text box>.value="", but it doesn't work.

4

1 回答 1

1

As discussed in the comments, this answer assumes you have wrapped a fieldset around each grouping of radio buttons and text box:

var sets = document.getElementsByTagName('fieldset'),
    setsCount = sets.length,
    clearBox = function (box) {
        box.value = '';
    },
    clearFields = function (fieldset) {
        var buttons = fieldset.querySelectorAll('input[type="radio"]'),
            buttonCount = buttons.length,
            textBox = fieldset.querySelector('input[type="text"]'),
            j;

        for (j = 0; j < buttonCount; j += 1) {
            buttons[j].onclick = function () {
                clearBox(textBox);
            };
        }

        textBox.onkeypress = function () {
            for (j = 0; j < buttonCount; j += 1) {
                buttons[j].checked = false;
            }
        };
    },
    i;

for (i = 0; i < setsCount; i += 1) {
    clearFields(sets[i]);
}

Demo

于 2013-05-15T11:02:48.213 回答