Jquery get value of checked radio button on load or change
Gets this script, which gets the value of the checked radio button and prints it out in another tag. It works great when you click the radio button, but I figured I needed some of the radio buttons to be checked by default.
How do I change this script so that it also outputs the values of already checked radio buttons on page load?
$("input[type='radio']").click(function(){
var radioValue = $(this).val();
if(radioValue){
$(this).closest('section').find('h2 .value').text(radioValue);
}
});
source to share
You can use a selector :checked
to find all checked items :radio
on load, and loop over them to set the value of the associated item .value
. Try the following:
$(":radio:checked").each(function() {
$(this).closest('section').find('h2 .value').text(this.value);
});
Note that you must use an event change
to bind to radio and checkbox elements to serve those navigating websites using their keyboards. Also, if you remove the check that the radio element has a value (which is redundant, since it should always matter), you can simplify your code:
$("input[type='radio']").change(setText); // when user selects
$(":radio:checked").each(setText); // onload
function setText() {
$(this).closest('section').find('h2 .value').text(this.value);
}
source to share