Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting current element in onKeydown function

i am writing a function which will be called when a key is down on keyboard how to access value of that textbox in which key is pressed. my code is

function isValid(evt,that){

console.log('coming to this 1');
var charCode = (evt.which) ? evt.which : event.keyCode;
console.log(that.val());
return true;
}

$(document).on('keydown','.is_valid',isValid);

how to get the value of textbox which is currently getting input from keyboard ?? please guideline How to accomplish this

like image 447
Ritesh Mehandiratta Avatar asked Jul 17 '26 05:07

Ritesh Mehandiratta


1 Answers

I'd suggest:

function isValid(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode,
        self = evt.target;
    console.log(self.value);
    return true;
}

$(document).on('keydown', '.is_valid', isValid);

JS Fiddle demo.

So long as the event is available to the function, you can access the target of that event with the appropriately-named event.target. If you need that to be a jQuery object, with access to jQuery methods you can use: $(event.target).

You could also use:

self = evt.currentTarget;

JS Fiddle demo.

Or:

self = document.activeElement;

JS Fiddle demo.

References:

  • document.activeElement.
  • event.currentTarget.
  • event.target.
like image 193
David Thomas Avatar answered Jul 18 '26 19:07

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!