Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - check if user is editing text input

Can you check if the user is editing a text field without editing anything? I want a function to be called when the user is in a text field and presses enter. I know it would work with a form.

Coffee:

$(document).keyup (e) -> 
  func()  if e.which is 13 and "user is in input field"

Javascript:

$(document).keyup(function(e) {
    if(e.which == 13 and "user is in input field") {
        func();
    }
});
like image 754
hansottowirtz Avatar asked Mar 21 '23 07:03

hansottowirtz


2 Answers

You can use jQuery's .on() method to create a delegated event handler that is bound to the document but only calls your handler function if the target element matches a selector of your choice:

$(document).on('keypress', 'input[type="text"],textarea', function(e) {
    if (e.which === 13) {
        // do something here
    }
});

(This is similar to Musa's answer, except jQuery does the .is() test for you automatically.)

Note the selector in the second argument is 'input[type="text"],textarea' so as to exclude non-text inputs.

like image 64
nnnnnn Avatar answered Mar 23 '23 21:03

nnnnnn


I would check if the input field in on focus using jQuery:

var selectedInput = null;
$(function() {
    $('input, textarea, select').focus(function() {
        selectedInput = this;
    }).blur(function(){
        selectedInput = null;
    });
});
like image 45
Yair Nevet Avatar answered Mar 23 '23 22:03

Yair Nevet