JSFiddle - React, Tailwind, and code Playground
radio button checked call function
by oktaviardi pratama
HTML
<fieldset><legend>Demo</legend>
<label><input type="radio" id="one" name="group1">One</label>
<label><input type="radio" id="two" name="group1">Two</label>
</fieldset>
<fieldset><legend>Demo with more buttons</legend>
<label><input type="radio" id="g2A" name="group2" checked>A</label>
<label><input type="radio" id="g2B" name="group2">B</label>
<label><input type="radio" id="g2C" name="group2">C</label>
<label><input type="radio" id="g2D" name="group2">D</label>
<label><input type="radio" id="g2E" name="group2">E</label>
</fieldset>
<fieldset><legend>Demo with class changes</legend>
<label><input type="radio" id="car" name="group3">Caramel</label>
<label><input type="radio" id="cho" name="group3">Chocolate</label>
<label><input type="radio" id="van" name="group3">Vanilla</label>
</fieldset>
<p>Note that no "deselect" is sent if there was no previously checked radio button (as at initial page load).</p>
CSS
label.selected { background-color : blue; }
JavaScript
function setupDeselectEvent() {
var selected = {};
$('input[type="radio"]').on('click', function() {
if (this.name in selected && this != selected[this.name])
$(selected[this.name]).trigger("deselect");
selected[this.name] = this;
}).filter(':checked').each(function() {
selected[this.name] = this;
});
}
$(document).ready(function() {
setupDeselectEvent(true);
$('input[name="group1"]').on('deselect', function() {
alert('Radio ' + this.id + ' deselected');
});
$('input[name="group2"]').on('deselect', function() {
alert('Group 2 radio ' + this.id + ' deselected');
}).on('change', function() {
alert('Group 2 radio ' + this.id + ' selected');
});
$('input[name="group3"]').on('deselect', function() {
$(this).parent().removeClass("selected");
}).on('click', function() {
$(this).parent().addClass("selected");
});
});