Solved

narrow down a lot of select options using jquery

Posted on 2014-03-31
13
847 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:Neil Thompson
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 43

Expert Comment

by:Rob
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 43

Expert Comment

by:Rob
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 43

Expert Comment

by:Rob
ID: 39968681
Thanks but what's invalid?
0
 
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 43

Expert Comment

by:Rob
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 43

Expert Comment

by:Rob
ID: 39968724
Very true :-)
0
 
LVL 3

Author Closing Comment

by:Neil Thompson
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 43

Expert Comment

by:Rob
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

Report: Liquid Web beats Amazon, Rackspace & More

A study by performance analyst firm Cloud Spectator finds that Liquid Web beats rivals Amazon, Rackspace and DigitalOcean when it comes to website and cloud application performance.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SharePoint and CAML query help 4 26
Where is this content coming from? 4 40
Horizontal Full Calendar using php 5 45
Submit button if clicked twice submits twice 1 25
PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…

710 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