Javascript hide/show classes with checkbox
I am just learning javascript, so please bear with me!
I want to be able to use checkboxes to choose to hide/show div classes (to basically filter the amount of info being shown). It is done in this... but I'm try to figure out something much simpler (since I don't need to dynamically generate the checkbox options.)
I came across this example: The Javascript:
function showMe (it, box) {
var vis = (box.checked) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
The HTML
<form>
<input type="checkbox" checked="checked" value="value1" onclick="showMe('div1', this)" />value1
<input type="checkbox" checked="checked" value="value2" onclick="showMe('div2', this)" />value2
<input开发者_开发问答 type="checkbox" checked="checked" value="value3" onclick="showMe('div3', this)" />value3
</form>
<div id="div1" style="display:block">Show Div 1</div>
<div id="div2" style="display:block">Show Div 2</div>
<div id="div3" style="display:block">Show Div 3</div>
</body>
</html>
But it only works for div ids, not classes. Any idea on how I can work this?
Thanks in advance if you can help me out!
At the moment, you're probably best off using a library like Prototype, jQuery, Closure, or similar for this sort of thing, as standardization for finding elements by class name (the document.getElementsByClassName
method) is relatively recent and it's not supported yet by at least one major browser (they document a way to add it, but not a very good one).
In Prototype, the $$
function searches by a large subset of the CSS3 selectors draft proposed recommendation. In jQuery, the $
function does much the same thing (via the Sizzle selector engine, which can also be used on its own, weparate from jQuery).
In Prototype, you can show or hide elements by class like so:
$$('div.myClassName').invoke('hide'); // Hides all matches
$$('div.myClassName').invoke('show'); // Shows all matches
In jQuery, it's:
$('div.myClassName').hide(); // Hides all matches
$('div.myClassName').show(); // Shows all matches
精彩评论