vendredi 29 mai 2015

HTML Elements display:initial or display:none changing upon checkbox state

I have created a little set-up with

and elements, which I want to either be shown or hidden depending on the state of their designated checkbox. When the checkbox is checked, display:intial should be set, when the checkbox is unchecked, display:none should be set. However, I've been trying to find out how to do this with JS, but I haven't gotten anywhere. An example of the code I have:

    <p id="nr_1" style="display:initial"> Number 1 Example text here </p>
    <input type="checkbox" id="nr_1" checked > Number 1</input> 
    <p style="display:initial" id="nr_1"> <img src="src_nr_1.png"> </p>

The JS I've managed to scramble together from what I could find look like this:

    function handleClick($id) {
    if (document.getElementById($id).display == checked) {
    var element = document.getElementById($id);
    element.style = "display:initial";
    else {
    var element = document.getElementById($id);
    element.style = "display:initial"; }

However, I haven't even been able to succesfully have the checkbox do ANYTHING. I've tried it with If/Else simply popping up an alert with texts to see if I had been able to have anything happen upon checking and unchecking the checkbox. It's probably very obvious from the constructions I've been building, but I've never used JS before. I imagine it has to do something with onClick() or onCheck(), but neither have seemed to respond to anything at all.

So what I'm trying to do here is have the JS react upon checking/unchecking a checkbox. I'd like to keep it as general as possible, because there's going to be somwhere between 10-25 checkboxes, and having to hardcode it for every different HTML element wouldn't be the most ideal situation. The checkbox, Text element and Image all have the same ID to match them with. So if Checkbox 1 gets checked, Text element 1 and Image 1 will appear. If it get's unchecked, they both disappear. Anything to point me in the right direction would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire