简体   繁体   中英

Is it possible to make a radio button de-selectable in JSP (like checkbox)

Is it possible to make a radio button de-selectable in JSP (like checkbox)?

I have a page with a coulmn of table having radio buttons. i want to de-select the radio button if i click it on selected radio. Here is the code

<tr>                    
<TD><INPUT type="radio" name="Radios" value="someValue"></td>
<TD>someValue</td>
</tr>

Thanks in advance.

You could use Javascript to set/switch the attribute checked valued as "checked" (the button is selected) or "" (empty stinrg = the button is not seleceted) based on mouse click events. Here is a reference doc about radio buttons .

Keep in mind that only one radio button in a group can be selected at a time.

Try this javascript code:

var firstClick = true;
function tick(element){
 if(!firstClick){
     if(element.checked){
         element.checked = false;
         firstClick = true;
     }
 }else{
     firstClick = false;
 }

}

then add the onclick property

<tr>                    
<TD><INPUT type="radio" name="Radios" value="someValue" onclick="tick(this);"></td>
<TD>someValue</td>
</tr>

Note: This is not tested. But this should work.

The problem is that the unchecked button becomes checked right after the click before the onclick handler run. So even if the button was unchecked before the user clicks it it becomes checked when the handler is started. So the code below will not work.

function toggle(e)
{
    e.checked = !e.checked;
}

So there is a trick to avoid this issue. We just add a field which counts the parity of clicks.

function toggleRadioButton(e)
{
    if(e.parity==undefined)
    {
        e.parity = false;
    }
    e.parity = !e.parity;
    e.checked = e.parity;

    //Fix parity of other buttons of this group which are unchecked automatically
    if(e.checked)
    {
        var buttonsInGroup = document.getElementsByName(e.name);
        for(var i=0; i<buttonsInGroup.length; i++)
        {
            if(buttonsInGroup[i]!=e)
            {
                buttonsInGroup[i].parity = false;
            }
        }
    }
}

HTML part will have the standard onclick handler:

<INPUT type="radio" name="Radios" value="someValue" onclick="toggleRadioButton(this)"/>

However there may be some integrity issues when changing the state of the button programmatically. I really dislike this code but don't see any other solutions.

Finally my suggestion would be not to use radio buttons in this strange way :).

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