I am looking for a safe way to get value of a selected radio button :
- I do not know the form id
- I do not know how much similar (ids excluded) form I have in my page
I am currently using this :
if (($(elem).is('input[type="radio"]')) && ($(elem).attr('name') !== undefined)) {
return $('input[name="' + $(elem).attr('name') + '"]:checked').val();
}
But this is not working if I have similar names in distinct forms, and I don't even know if this is safe to put such a thing on a selector.
My goal is to create a getValue()
function that returns value of one element ($(elem).length == 1
) without a matter of nature :
var getValue = function(elem) {
if ($(elem).is('input[type="checkbox"]')) {
return ($(elem).prop('checked') == true);
}
else if (($(elem).is('input[type="radio"]')) && ($(elem).attr('name') !== undefined)) {
return $('input[name="' + $(elem).attr('name') + '"]:checked').val();
}
else if ($(elem).prop('value') !== undefined) {
return $(elem).val();
} else {
return $(elem).html();
}
}
Any suggestion ?