0

There are few similar questions in here, but none of them fits me.

I need an effective way to filter options in on select depending on selected value in another select. First select consist of options with simple numeric values 1,2,3... The second one, which should be filtered, consist of options in 'groups'. The values of options are in hundreds i.e. 102, 103, 202, 254...

If the option with value 1 is selected only options with value starting with 1 should be visible in the second select. And this should happen every time user selects one option.

I've tried this piece of code, but it doesn't work.

function filterInstitution(elem){ var currRow = elem.closest("tr") var inType = elem.val(); currRow.find(".CompName option").toggle(false); currRow.find(".CompName option").each(function(){ $("[value^="+ inType + "]", $(this)).toggle(true); }); } 

Here's the Fiddle. It only contains few options, but in reality, the second select consist of 80+ options.

My idea was to hide all options and show only options starting with selected number from the first select. Where did i go wrong?

3 Answers 3

1

When you say

$("[value^="+ inType + "]", $(this)) 

You're telling jQuery to find the elements that meet the criteria "[value^="+ inType + "]" and that are also descendents of $(this). What you want to do instead is check that $(this) meets the criteria.

Here is a different version:

var currRow = elem.closest("tr") var inType = elem.val(); currRow.find(".CompName option") .hide() //equivalent to .toggle(false) .filter("[value^="+ inType + "]") //this will do the filter you desire .show(); //equivalent to .toggle(true) 

Fiddle Here: http://jsfiddle.net/pz9cjmLg/4/

Sign up to request clarification or add additional context in comments.

Comments

0

If I'm not mistaken, only Firefox supports the hiding of individual <option>s. I think you'll need to remove the options you don't wan't to show.

1 Comment

Lucky for us, Firefox is the only browser we support.
0

try

$(document).ready(function () { $(".CompType").change(function () { filterInstitution(this) }); }); function filterInstitution(elem) { var value = elem.value; var options = $(".CompName option"); options.hide(); var op = options.filter(function () { return value == $(this).val().slice(0, 1); }).show(); $(".CompName").val(op.eq(0).val()); } 

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.