1

My jQuery is starting to get unnecessarily long. Is there a way to easily combine these 2 functions. My first thought is to create a custom event out of the key down function. Any solutions or suggestions on what to read up on would be appreciated.

$('th:nth-child(3):first').click(function () {
    $('#dtSelect').val(2).change();
});

$('th:nth-child(3):first').keydown(function(event){    
    if(event.keyCode==13){
       $('#dtSelect').val(2).change();
    }
});
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
user262430
  • 229
  • 3
  • 17

2 Answers2

3

Simply:

$('th:nth-child(3):first').on('change keydown', function(event) {    
    if(!event.keyCode || event.keyCode==13){
       $('#dtSelect').val(2).change();
    }
});

This will fire on both change and keydown events, and will only call change() if event.keyCode does not exist (change) or is equal to 13 (keydown).

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • It works I just needed to change the "change" to "click". Thank you. – user262430 Jan 20 '15 at 15:35
  • JamesDonnelly - If you have time could you possibly explain what is going on in this line of code so I know for the future " if(!event.keyCode || event.keyCode==13){ ". specifically what do the "!" and "||" do. I am fairly new to this. – user262430 Jan 20 '15 at 15:39
  • 2
    The "!" means not (true => false and vice-versa) and the "||" means OR. See a small explanation here: http://stackoverflow.com/questions/4576867/javascript-or-operator-with-a-undefinded-variable – Shelby115 Jan 20 '15 at 15:56
2
function combined(event) {
    if (typeof event === 'undefined' || event.keyCode==13)
        $('#dtSelect').val(2).change();
}

$('th:nth-child(3):first').click(combined).keydown(combined);

although in this case I don't think it's worth combining them.

lukevp
  • 705
  • 4
  • 16