Jump to content

RadioButton: If value is not selected, it shows that selected the last? (jQuery)


Recommended Posts

 <p><input type="radio" name="type_select" value="1" class="styled" /> 111</p>
<p><input type="radio" name="type_select" value="2" class="styled" /> 222</p>
<p><input type="radio" name="type_select" value="3" class="styled" /> 333</p>

 

I would like to check if user have selected any value like this:

 

alert($("input[@name='type_select']:checked").val()); // if value not selected it alerts "3", and no matter if page is refreshed or just entered

if ($("input[@name='type_select']:checked").val() == "unidentified")
{
alert("Please select any value.");
}

I don't use JQuery, but I suspect it has the same quirks when dealing with radio groups as when using straight JavaScript. Radio groups are just that - groups. As such the group is referenced as a single opbject with multiple child objects - much like an array. You cannot reference the group to see if any single option is selected. You have to check each option.

 

The easiest solution is to just check one of the optins by default as it is impossible (from the UI perspective) to unselect all th eoptions. You can only select a different option.

 

If you stil lwant to have them all unchecked to begin with, then you will need to iterrate through each of the options to see if one is selected. Here is a javascript function I use to return the selected value of a radio group. If none are selected, the function returns false. You might be able to rewrite that for JQuery.

 

function radioGroupValue(groupObj)
{
    //Check if ther is only on option (i.e. not an array)
    if (!groupObj.length)
    {
        //Only one option in group
        return (groupObj.checked) ? groupObj.value : false;
    }

    //Multiple options, iterate through each option
    for (var i=0; i<groupObj.length; i++)
    {
        //Check if option is checked
        if (groupObj[i].checked)
        {
            //Return value of the checked radio button
            return groupObj[i].value;
        }
    }

    //No option was selected
    return false;
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.