Search code examples
javascriptjquerythisapplybind

How to apply keyup() function to different DOM element with different input correctly?


I'm trying to limit different min and max input of the day, month and year input of date of birth. However it seems there's something wrong with "this" in the function. May I know what is the correct and good way to write this function? I tried arrow function but it does not work. Should I use bind? Thank you so much!

$(document).ready(function () {
 var minMonth = 1;
 var maxMonth = 12;
 var minDay=1;
 var maxDay=31;
 var minYear=1900;
 var maxYear=2019;

 function minMaxDob(minDob, maxDob){
        if($(this).val() > maxDob){
            $(this).val(maxDob);
          }
        if($(this).val() < minDob){
            $(this).val(minDob);
          }
      }

 $("#dob_month").keyup(function(){
    minMaxDob(minMonth,maxMonth);
 });
 $("#dob_day").keyup(function(){
    minMaxDob(minDay,maxDay);
 });
 $("#dob_year").keyup(function(){
    minMaxDob(minYear,maxYear);
 });
});

Solution

  • You have to pass the jQuery object to the minMaxDob like the following, you have to do this because "this" refers to the currently executing function, since you are calling a helper function "this" no longer refers to the DOM object, but to the function minMaxDob:

    $(document).ready(function () {
      var minMonth = 1;
      var maxMonth = 12;
      var minDay=1;
      var maxDay=31;
      var minYear=1900;
      var maxYear=2019;
    
      function minMaxDob(jqObj, minDob, maxDob){
        if(jqObj.val() > maxDob){
            jqObj.val(maxDob);
          }
        if(jqObj.val() < minDob){
            jqObj.val(minDob);
          }
      }
    
      $("#dob_month").keyup(function(){
        minMaxDob($(this),minMonth,maxMonth);
      });
      $("#dob_day").keyup(function(){
        minMaxDob($(this),minDay,maxDay);
      });
      $("#dob_year").keyup(function(){
        minMaxDob($(this),minYear,maxYear);
      });
    });