pertrai1
pertrai1

Reputation: 4318

jquery filter from drop down

I was wondering how I would create an option to filter content based off of a drop down. I am not looking for a plugin, as long as this is not something that is difficult. here is an example of what I need to do when a selection is selected from drop down:

<select name="division-select" id="division-select">
 <option value="halter">Halter</option>
 <option value="english">English</option>
</select>

<div>
 <p class="halter">halter class 1</p>
 <p class="halter">halter class 2</p>
 <p class="english">english class 1</p>
 <p class="english">english class 2</p>
</div>

So what I would like to happen is when there is a select from the drop down box, the option that is selected would automatically hide any paragraphs that do not have the class that does not have the class that equals the option value.

Is this possible?

Thank you for any help on this.

Rob

Upvotes: 0

Views: 4799

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

$("#division-select").bind("change", function() {
    $("." + this.value).show();
    $("p:not(." + this.value + ")").hide();
});

Here's a working example: http://jsfiddle.net/andrewwhitaker/KcStv/

Notes:

  • Binds an event handler to the change event of the select element.
  • Calls show() on the element who's class is equal to that of the current value of the select (this.value).
  • hide()s the other p tags without that class using the :not selector.

Upvotes: 3

alex
alex

Reputation: 490153

$('#division-select').change(function() {
    var matches = $('div > p.' + $(this).val());
    matches.show().siblings().not(matches).hide();
});

jsFiddle.

If you want this to do its magic at load, chain change() after the event is attached to trigger it.

Upvotes: 0

Related Questions