Reputation: 1345
A bit of a struggle here. My eventlistener only detects the "checked" change of my radio button, not the "unchecked" change. Note: Pure javascript (vanillajs) only, no jQuery.
A little JSFiddle to explain my problem: https://jsfiddle.net/kLuba37w/1/
<label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" data-show-more data-target="showmoretarget2" value="1"> <span></span> This is the first radio
</label>
<label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" value="2"> <span></span> This is the second radio
</label>
<div class="js-show-more" data-hook="showmoretarget2">
<h2 class="h2"> Some more content</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis ipsum repellendus, officia dolores consectetur. Error at officiis sequi iure earum.</p>
</div>
JS:
(function() {
"use strict";
var elements = document.querySelectorAll('[data-show-more]');
[].forEach.call(elements, function(element) {
element.addEventListener('change', function(e) {
e.preventDefault();
var target = document.querySelectorAll('[data-hook="' + this.getAttribute('data-target') + '"]')[0];
alert("change detected");
}, false);
});
})();
Upvotes: 3
Views: 7327
Reputation: 45
document.getElementsByName('radio-button').forEach(function(element) {
element.onclick = function() {
alert("Click detected in button #" + element.value);
}
});
<fieldset>
<div>
<input type="radio" name="radio-button" id="button1" value="1" checked>
<label for="button1">This is the first radio</label>
</div>
<div>
<input type="radio" name="radio-button" id="button2" value="2">
<label for="button2">This is the second radio</label>
</div>
</fieldset>
Upvotes: 1
Reputation: 1258
Easy way to do this, is to listen checked event an all radio buttons with name radio
(function() {
"use strict";
document.querySelector("#radio1").addEventListener("change", function() {
alert("checked radio 1");
});
document.querySelector("#radio2").addEventListener("change", function() {
alert("checked radio 2");
});
})();
Upvotes: 6