dimanche 1 juillet 2018

How to show specific text if one specific checkbox is checked among bunch of unique checkboxes

I have a specific task to do, and i'm not sure what is the best way to do it. I have around 60 checkboxes (each of them unique) and i have to, when clicked on a specific checkbox, make one specific text display on the right side (that is tied to that clicked checkbox). I have done it with 64 specific eventListeners, but i'm not sure that this is the best way.

One more thing, i'm pretty new at javascript and this is more of a practice than a project. For now, since it's working, perfect, but i want to simplify the code in order to do what is needed.

So, for example, i have bunch of checkboxes in a label that is: test, test1, test2 and so on. and when i click on test checkbox, that the text: "hello world" can appear, if test1 is checked, text: "One 2 three" can appear, if test2 is checked, text: "I've done it" can appear, but if none of them is selected, texts will not be displayed.

This is the code, one event listener i have now:

var forSale = document.querySelector('#for_sale');
var forSaleEmail = document.querySelector('#for_sale_email');
/*For Sale*/
forSale.addEventListener("click", function(){
    if(forSale.checked === true){
        forSaleEmail.style.display = 'block';
    } else {
        forSaleEmail.style.display = 'none';
    }
});

Where forSale variable is a checkbox and forSaleEmail is a text that should be displayed.

If you have any suggestions or you can tell me what to look for, it would be greatly appreciated.

HTML Code is following:

<label>For Sale <input type="checkbox" id="for_sale"></label>
<span id="for_sale_email">
<p>
for sale
</p>
</span>                            




Aucun commentaire:

Enregistrer un commentaire