jQuery - reusing change() function

jagku
jagku used Ask the Experts™
on
Hello Experts,

If someone can give me advice on the following.

I have several selects:

<select id="search_1_unit">
...
</select>
<select id="search_1_m">
...
</select>

<select id="search_2_unit">
...
</select>
<select id="search_2_m">
...
</select>


<select id="search_3_unit">
...
</select>
<select id="search_3_m">
...
</select>


When the user selects a 'unit', I have an .change() jquery function that kicks in and dynamically populates
the search_1_m select.

ie
      $('#search_1_unit').change(function() {
      
      };
      

How do I rewrite this so that I don't have to write a
new function for each select.

ie I don't want to code:

      $('#search_2_unit').change(function() {
      
      };
      
      $('#search_3_unit').change(function() {
      
      };      
      
etc

Many Thanks as always!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
You may use : $('select').change(function() {
http://api.jquery.com/element-selector/

Or : $("select[id^='search_']").change(function() {
http://api.jquery.com/attribute-starts-with-selector/
$('select[id^="search_"]').change(function() {
      alert( $(this).attr("id") );
      //
});

Open in new window

leakim971Multitechnician
Top Expert 2014

Commented:
Thanks for the points!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial