Solved

narrow down a lot of select options using jquery

Posted on 2014-03-31
13
800 Views
Last Modified: 2014-04-03
Hi

I'm trying to narrow down what will be a massive list of schools when a user selects the borough

I've added the search criteria to the school list in the name column as I need to post the actual values in the end.

I'm not sure 'm using the jQuery syntax corectly here as I've never tried this before so hoping one of you gurus can assist

Regards
Neil

$('#borough').change(function() {
    alert(this.value);
	$( "#school option[name!='"+ this.value +"']").hide(); 
})

Open in new window


<label for="borough">Borough</label>

<select id="borough" name="borough">
    <option value="">SELECT</option>
    <option value="303">bex</option>
    <option value="305">bro</option>
    <option value="203">gre</option>
    <option value="886">knt</option>
</select>

<label for="school">School</label>

<select id="school" name="school">
    <option value=""><-- Select borough first to narrow down</option>										
    <option value="2012" name="305">test school 1</option>										
    <option value="6079" name="305">test school 2</option>											
    <option value="2013" name="305">test school 3</option>        
    <option value="6000" name="303">test school 4</option>										
    <option value="5200" name="303">test school 5</option>											
    <option value="5201" name="303">test school 6</option>									
    <option value="2088" name="886">test school 7</option>										
    <option value="3896" name="886">test school 8</option>        
    <option value="7034" name="886">test school 9</option>		        
    <option value="3666" name="203">test school 10</option>							
    <option value="4250" name="203">test school 11</option>									
    <option value="2662" name="203">test school 12</option>
</select>

Open in new window


code example at http://jsfiddle.net/ihategherkins/DwrTH/
0
Comment
Question by:NeilT
  • 6
  • 6
13 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39968421
1. never use alert in a change event. Instead use
window,console && console.log(this.value)

2. options do not have a name attribute

I would add the borough to the school values and use value^=borough

Normally one would have an object with arrays per borough and re-populate the other select. Also it is possible to hide the other select when nothing is selected in the first one to stop the possibility of selecting no borough and random school
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 39968455
Actually as it turns out, you cannot hide or show options cross browsers.

This code only works in Firefox:

http://jsfiddle.net/mplungjan/44Pbr/

$('#borough').on("change",function() {
    window.console && console.log(this.value);
    $( "#school option").hide();	
    $( "#school option[value^='"+ this.value +"']").show(); 
})

Open in new window


This code works in all browsers:

http://jsfiddle.net/mplungjan/9ZT3s/

var boroughs = {
  305 : {
    name:"bro",
    schools: [
        {val:2012,name:"test school 1"},
        {val:6079,name:"test school 2"},
        {val:2013,name:"test school 3"}
      ]
    },
  303: { 
    name:"bex",
    schools: [
        {val:6000,name:"test school 4"},
        {val:5200,name:"test school 5"},
        {val:5201,name:"test school 6"}
      ]
    }     
}

$(function() {
  $.each(boroughs,function(num,borough) {  
    $('#borough').append('<option value="'+num+'">'+borough.name+'</option>'); 
  });      
  $('#borough').on("change",function() {
    var br = this.value, $schoolDrop=$("#school");
//    window.console && console.log(br);
    $("option:gt(0)",$schoolDrop).remove(); // remove all options except the first
    if (br) { // does the borough have schools
      $("option:eq(0)",$schoolDrop).text("Please select school for "+boroughs[br].name);
      var schools = boroughs[br].schools;
      $.each(schools,function(_,school) {
        $schoolDrop.append('<option value="'+school.val+'">'+school.name+'</option>');          
      });  
    }    
    else {
      $("option:eq(0)",$schoolDrop).text("<-- Select borough first to narrow down");
      }  
  });
});

Open in new window

0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39968486
Modified it slightly (http://jsbin.com/rinuh/1/edit)

.hide() only works in firefox for option elements... it's not cross browser

So you have to save the original state of the list and reset it between searches

I used the same html as you but with the following javascript:

$(function() {
var myNS = {};  // use a namespace
$('#borough').change(function() {
    myNS.resetList();
  $( "#school option[name!='"+ this.value +"']").remove(); 
});
myNS.mylist = $("#school").html();
myNS.resetList = function() {
   $("#school").html(myNS.mylist);
};
});

Open in new window


I also touch on namespaces in this article: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_13138-Javascript-is-just-an-Object.html
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39968488
(Sorry mplungjan - I posted my comment before I realised you'd responded)
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39968675
Quite elegant solution except for the use of invalid attribute name

Also if there are a lot of schools, you are hammering the DOM

Lastly I also change the 0th option to "Please Select" and "<-- please select borough first"
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39968681
Thanks but what's invalid?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39968687
The name attribute is invalid

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option

Attributes
This element includes the global attributes.

disabled
label
selected
value
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39968695
Arghh *head slap*
Well done, I'm not even sure why it worked.
Definitely should be changed to value from name.
I would still use the != operator for an exact match.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39968712
If you have a value of

303_6912, then
 $( "#school option[value^='"+ this.value +"_']").show();

would be precise too :)
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39968724
Very true :-)
0
 
LVL 3

Author Closing Comment

by:NeilT
ID: 39971753
Many thanks all for your great comments, my knowledge increases daily from your assistance

This one was perfect for my specific needs though.

Neil
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39972020
You are wekcome. Thanks for the kind words. As it turns out I also learned something
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 39973637
Thank you as well for the comments. I like to think that's the site is about. It would be rare that I'd participate in a question and not learn something too
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
jQuery or CSS 9 38
Responsive CSS question 2 42
lastpass auto fill login form 5 24
Css issue on scroll 1 18
There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now