Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show div when radio button checked vanilla js

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);

  });

 })();
like image 498
Warre Buysse Avatar asked Nov 01 '25 10:11

Warre Buysse


2 Answers

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");
    });

})();
like image 108
Profesor08 Avatar answered Nov 03 '25 01:11

Profesor08


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>
like image 32
user22009348 Avatar answered Nov 03 '25 02:11

user22009348