Sometimes, we need to get the selected value from a radio button group on the client side for validation purpose. But as all radio input elements have same name attribute its not possible to get its value with document.formname.elementname.value javascript property. Here actually you have to iterate through all radio button elements & get the selected one.The following small code-snippet will help you to find out the selected radio button's value from a html form with javascript:
function get_value(form_object,groupname)
{
var i = 0;
while (e = form_object.elements[i++])
{
if(e.name == groupname && e.checked)
return e.value;
}
return -1;
}
change the bold words with your own form object reference & radio button group's name. It will be an independent code which you can use/reuse several times.
Also, if you are using jquery library, there will be most simpler solution. Then, simply use the following line of code:
$("input[type='radio'][name='"+groupname +"']:checked").val();
SO, you just got the solution to remove all your headache to manipulate radio input's value with client site javascript.
Subscribe to:
Post Comments (Atom)










0 comments:
Post a Comment