Combining changes, mouse, mouse, mouse, keyboard and input into one function

What I have:

  • I have a text field that assumes the value of any option in the corresponding selection field.
  • I repeat the same function for change events, mouseup, mousedown, mouseout, keyup and keydown

What I need:

Is it possible to combine the above functions into one to create more efficient code? It just seems horribly repetitive.

My code is:

JSFiddle: http://jsfiddle.net/clarusdignus/843YW/1/

HTML:

<label>Industry:</label> <select name="industry"> <option selected="selected"></option> <option value="ag">Agriculture</option> <option value="co">Corporate</option> </select> <input type="text" disabled="disabled" name="industryspecifier"/> 

JQuery

 $('select[name=industry]').on('change', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); $('select[name=industry]').on('mouseup', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); $('select[name=industry]').on('mousedown', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); $('select[name=industry]').on('mouseout', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); $('select[name=industry]').on('keydown', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); $('select[name=industry]').on('keyup', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); 
+7
javascript jquery
source share
1 answer

Just combine them with spaces:

 $('select[name=industry]').on('change mouseup mousedown mouseout keydown', function() { $('[name=industryspecifier]').val($(':selected',this).val()); }); 

JsFiddle example

Like docs for .on () :

events Type: String One or more types of events separated by spaces, and optional namespaces such as "click" or "keydown.myPlugin".

+9
source share

All Articles