Filter is used to filter some results from a set. (of course) For example let’s have a document with many divs in it. We want to select only the ones with css class “.text” and hide them. We can do this using filter.
At the beginning lets write some dummy html file with the basics in it. Here it is our filter.htm:
<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {
}
.comment {
}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
// our javascript examples will go here
});
</script>
</head>
<body>
<!-- our text will go here -->
</body>
</html>
Let’s make some divs and set class text to some of them and comment to the others.
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>
This row will hide all divs with class text.
It would be easy to make a button that shows and hides these divs. Here is the full source:
<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {
}
.comment {
}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#toggle").click(function() {
$("div").filter(".text").toggle();
});
});
</script>
</head>
<body>
Show and hide filtered divs. <br />
<button id="toggle">Toggle Show/Hide</button>
<div class="comment">
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>
</body>
</html>
Here is our work:
Show and hide filtered divs.
Intro to JQuery - part 1
Intro to JQuery - part 2
No comments:
Post a Comment