Combining .change() and keyup

1.1k views Asked by At

I have two functions that I would like to combine into one. Is it possible to combine...

$(document).ready(function () {
   $(".jobtype").change(function () {
      if ($("select[name='jobtype']").val() != "Low Budget") {
         // something happens
      }
   });
});

and this...

$(document).ready(function () {
   $(document).on('keyup', function (evt) {
      if (evt.keyCode == 27) {
         // same thing happens
      }
   });
});

so that they work for both change() and keyup?

EDIT: Sorry I wrote this post really late at night so maybe wasn't explaining myself properly.

I have a form, that when the option "Low Budget" is selected from a drop down select list, that a function runs that changes a bunch of stuff on the page.

However, if the "Low Budget" option is deselected, then another script runs that undoes the changes and returns the page to its original form. This code to return it to original form is maybe 30 lines long.

I would like the same piece of code to run, if the user presses ESC and closes out of the form.

It seems strange to have the same function written out twice, so am wondering what is correct and most efficient way to code this. Part of me thinks that I could have the 30 lines of code written inside of something like

function doSomething() {
    // 30 lines of code
}

and then inside the two events have:

$(document).ready(function () {
    $(".jobtype").change(function () {
        if ($("select[name='jobtype']").val() != "Low Budget") {
            doSomething();
        }
    });
});

and

$(document).ready(function () {
    $(".jobtype").change(function () {
        if ($("select[name='jobtype']").val() != "Low Budget") {
           doSomething();
        }
    });
});

However I am unsure of the correct way to structure code.

Thanks again

4

There are 4 answers

1
Leo Silence On BEST ANSWER

Maybe this solution is not good enough, but you can try:

$(document).ready(function() {
    $(".jobtype").change(function() {
        if ($("select[name='jobtype']").val() != "Low Budget") {
            common();              
        }
    });

    $(document).on('keyup',function(evt) {  
        if (evt.keyCode == 27) {
            common();
        }
    });

   function common() {
     alert('1111'); // some common logic
   }
});
0
sachin kumar On

Maybe below solution:

    var $documentEle =  $(document);
    var sameFunction = function(callback) {
        $documentEle.ready(function() {
            $(".jobtype").change(function() {
                if ($("select[name='jobtype']").val() != "Low Budget") {
                    callback()
                }
            });
            $documentEle.on('keyup', function(evt) {
                if (evt.keyCode == 27) {
                    callback()
                }
            });
        });
    }

  function callbackFunction () { //code}

   sameFunction(callbackFunction);
0
Oka On

Definitely possible, but your conditional starts to get weird.

We let document handle all key events via propagation, so pressing ESC at any time will should fire the event handler.

For the input side of things we check that it's the actual element (.jobtype) changing, otherwise changing other elements will also propagate to the document and fire. Since document can't naturally fire a change event this works out fine.

DEMO

$(document).ready(function () {
  
  function myEventHandler (e) {
    var val = $("select[name='jobtype']").val();
    
    if (e.keyCode === 27 || 
        this === e.target && val === 'Low Budget') {
      // do something
      console.log('Did something...');
    }
  }
  
  
  $(document).on('keyup', myEventHandler);
  $('.jobtype').on('change', myEventHandler);
});
<select name="jobtype">
  <option value="nope">nope</option>
  <option value="Low Budget">Low Budget</option>
</select>

<input type="text" class="jobtype" />


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

I would probably advise against this pattern. Is there a reason you want to do it this way? There might be a better solution.

0
rxssmcdxwell On

I ended up doing this thanks to 'Alex Looks So Sad's answer.

$(document).ready(function() {
    $(".jobtype").change(function() {
        if ($("select[name='jobtype']").val() != "Low Budget") {
            undoEgg();
        }

    $(document).on('keyup',function(evt) {  
        if (evt.keyCode == 27) {
            undoEgg();
        }
    });

    function undoEgg(){
        // 30 lines of code
    }
});

This worked perfectly for what I was trying to achieve, thanks.