jQuery: Get and Set a Radiobutton Value
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<h2>Select a Pet</h2>
<div>
<input name="petu" type="radio" value="dog" /><span>Dog</span>
<input name="petp" type="radio" value="cat" /><span>Cat</span>
<input name="petl" type="radio" value="fish" /><span>Fish</span>
</div>
<fieldset>
<legend>Select a Pet with jQuery</legend>
<button id="selectDog">Select Dog</button>
<button id="selectCat">Select Cat</button>
<button id="selectFish">Select Fish</button>
</fieldset>
<div>
<button id="getPetValue">Get Pet Value</button>
</div>
<h2>Results</h2>
<div id="results">
</div>
<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:7" target="_blank">How To: jQuery - Get and Set a Radiobutton Value</a>
</div>
CSS
body > div, fieldset {
margin-bottom: 20px;
}
fieldset {
display:inline-block;
border: 1px solid lightgrey;
}
button {
margin-right: 10px;
}
#results {
min-height: 50px;
border: 1px solid lightgrey;
padding: 5px;
}
JavaScript
$(function () {
var $checkbox = $("#checkbox");
var $results = $("#results");
var count = 1;
$("#selectDog").on("click", function () {
var $radiobutton = $("input[value='dog']");
$radiobutton.prop("checked", true);
});
$("#selectCat").on("click", function () {
var $radiobutton = $("input[value='cat']");
$radiobutton.prop("checked", true);
});
$("#selectFish").on("click", function () {
var $radiobutton = $("input[value='fish']");
$radiobutton.prop("checked", true);
});
$("#getPetValue").on("click", function () {
var pet = $("input[name='pet']:checked").val();
var message = "";
if (typeof pet === "undefined") {
message = "A pet has not been selected";
} else {
message = "The pet that is currently selected is: " + pet;
}
$("#results").prepend("<div>" + count++ + ". " + message);
});
});