How do I access $(this).val() in another function by passing the reference from the onclick event?

Viewed 159

Current code:

function validateInput() {
  console.log($(this).val())
}

$("#element")
  .datepicker({
    todayHighlight: true,
    weekStart: 0,
    format: "yyyy-mm-dd",
    onClose: function() {
      validate.validateInput()
    }
  })

Outcome/Issue:

When I do this, I am getting nothing, even if I pick any date on the datepicker. I want to be able to get the current selected value if selected or null if not. Am I doing this correctly?

4 Answers

You should pass this to the function so that you can refer that inside the function to access the value. Also, not sure why you are using validate in validate.validateInput():

function validateInput(el){
  console.log($(el).val());
}
 
$("#element")
  .datepicker({
    todayHighlight: true,
    weekStart: 0,
    format: "yyyy-mm-dd",
    onClose: function() {
      validateInput(this);
    }
  });
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<p>Date: <input type="text" id="element"></p>

Pass it as an ordinary argument.

function validateInput(el) {
  console.log($(el).val())
}

$("#element")
  .datepicker({
    todayHighlight: true,
    weekStart: 0,
    format: "yyyy-mm-dd",
    onClose: function() {
      validateInput(this)
    }
  })

Well u could do like this:

function validateInput(element){

console.log($(element).val())
}

and call

    $("#element")
      .datepicker({
        todayHighlight: true,
        weekStart: 0,
        format: "yyyy-mm-dd",
        onClose: function() {
          validate.validateInput('#element');
        }
      });

or dinamically

$(".date_input")
          .datepicker({
            todayHighlight: true,
            weekStart: 0,
            format: "yyyy-mm-dd",
            onClose: function(e) {
              validate.validateInput(e.target);
            }
          });

Providing validate.validateInput() doesn't need this to refer to validate (eg to call other validate methods), then you can use Array.prototype.bind() to control the interpretation of this, without needing to pass a parameter.

function validateInput() {
    console.log($(this).val());
}

$("#element").datepicker({
    'todayHighlight': true,
    'weekStart': 0,
    'format': "yyyy-mm-dd",
    'onClose': validate.validateInput.bind(this)
});
Related