Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining change, mouseup, mousedown, mouseout, keyup and keydown into the one function

What I have:

  1. I have a text box that assumes the value of whatever option is selected in a corresponding select box.
  2. I'm repeating the exact same function for the on change, mouseup, mousedown, mouseout, keyup and keydown events

What I need:

Can the aforesaid functions be combined into one to produce more efficient code? It just seems terribly repetitious.

My code:

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());
});
like image 560
Clarus Dignus Avatar asked Apr 02 '14 20:04

Clarus Dignus


1 Answers

Just combine them with spaces:

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

jsFiddle example

As the docs for .on() state:

events Type: String One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".

like image 186
j08691 Avatar answered Oct 16 '22 11:10

j08691