How do I check if input field is in focus or not?

2020-07-18 06:53发布

I want to send an Ajax request only when my input field is in focus (i.e., cursor is inside it. Here's my code:

function anewFunc() {
    $(document).ready(function(){
        var chatattr = $(".chatwindow").css("visibility");
        var chattitle = $("#hideid").text();
        if (chatattr == "visible") {
            if (MY INPUT FIELD HAS FOCUS) {
                $.ajax({
                    url: 'seen1.php',
                    type: 'post',
                    data: "ctitle="+chattitle,
                    success: function(result9) {},
                    error: function() {}
                });
            }
        } else {
            $.post("seendefault.php");
        }
    });
}

$(document).ready(function(){
    var zzz = setInterval(anewFunc, 2000);
});

Now I don't know how to check every time the input has focus or not. Is there any jQuery solution for it?

EDIT: A few answers has suggested me :focus. So I tried this for trial:

$(document).ready(function(){
                           if($("#msgtypeid").is(":focus")){
                               alert("Hello");
                           }
                           });

HTML:

<form id="chatform" name="form4" method="post" required enctype="multipart/form-data">
          <input id="msgtypeid" type="text" name="cmessage" autocomplete="off" autofocus/>
        </form>

But it's not working. Is there something wrong?

8条回答
聊天终结者
2楼-- · 2020-07-18 07:16

I think you need this type of a checking:

var hasFocus = $('#idOfTheInputElement').is(':focus');
if(hasFocus){
    //logic here
}
查看更多
走好不送
3楼-- · 2020-07-18 07:18

Here is an example showing a few different options:

CodePen Example

HTML

<input type='text' class="is-focus">

<input type="text" class="isActiveElement">

<input type="text" class="focused">

JS

$('input').on('click', function() {

  if ($('.is-focus').is(':focus')) {
    alert('focused')
  }

  if ($(document.activeElement).is('.isActiveElement')) {
    alert('isActiveAlement')
  }

  if($('.focused:focus').length) {
    alert(':focus')
  }
});
查看更多
登录 后发表回答