-1

I have tried to change the classname in the parent class when input checkbox is "checked" in the child class with no luck. Need it to be done with javascript, no Jquery.

<div class="parentBox">
<img src="pic.png" alt="Small pic" class="notChecked">
    <div class="childBox">
        <img src="pic.png"" alt="Bigger pic">
        <input type="checkbox"><span>Sample picture</span>  
    </div>
</div>

I want to change the class name in the img tag in parentBox to "checked" when the input chechbox is checked. It will then change the css style so the user see that the image is selected. Try it out in the jsfiddle link.

Css code:

.notChecked {border: 1px solid black;}
.checked {border: 5px solid red;}

Here is jsfiddle link: http://jsfiddle.net/8LW6Q/

toby
  • 17
  • 6
  • If you are not using jQuery, you will need to do a lot of work. Start by looking at: http://stackoverflow.com/questions/9436123/javascript-changing-a-class-style and http://stackoverflow.com/questions/4754699/how-do-i-get-if-a-checkbox-is-checked-or-not You may need to assign a class to the `input` checkbox to facilitate navigationg the DOM. – Marc Audet Dec 12 '13 at 12:19

2 Answers2

1

based on your html:

document.querySelector('input[type=checkbox]').addEventListener('click', function(){
    var pointer = this, className = this.checked ? 'checked' : 'notChecked';

    while(!~pointer.className.indexOf('parentBox'))
                pointer = pointer.parentNode;

    pointer.querySelector('img[src="pic.png"]').className = className;
});

Reference: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

Marc Audet
  • 46,011
  • 11
  • 63
  • 83
Igor Benikov
  • 884
  • 6
  • 21
0

Here is the working Demo http://jsfiddle.net/8LW6Q/1/

You can and some javascript like this:

function funCalled(obj) {
  var el = document.getElementById("parentImg");
  if (obj.checked) {

    el.className = "checked"; 
  } else {
    el.className = "notChecked";
  }
}

Also you have to add id to img and onclick="javascript:funCalled(this)" to checkbox

spring
  • 760
  • 4
  • 10
  • Thanks for you answer. Helped alot. What if I have more then one pictures? With this solution its only change the first div class img. if I have three divs and hover over the second div and its change the classname for div 1. – toby Dec 13 '13 at 11:44
  • you can add for example data-img attribute to input. and add the same id to parent img. change js. here is the working demo http://jsfiddle.net/8LW6Q/4/ – spring Dec 18 '13 at 14:40