简体   繁体   中英

Alert on Input focus, which has no class or ID and is within a Div

How can I alert a message once the input is focused, of the following HTML code:

<div class="ss_datesel_inp_cont">
    <div class="ss_datesel_inp_right_corner"> </div>
    <input autocomplete="off">
</div>

This is what I tried but none works:

$(".ss_datesel_inp_cont:input").click(function() {
    alert("focused");
});

// or

$(".ss_datesel_inp_cont:input").focus(function() {
    alert("focused");
});

//or 

$(".ss_datesel_inp_cont").find("input").focus(function() {
    alert("focused");
});

The :input selector will only work if the the given element is an input (also textarea, select, and others). The .ss_datesel etc. class is not on the input, it's on the div. You can simply use a descendant selector instead:

$(".ss_date_etc input").click(function() { alert('focused'); });

However, this will only work if click the input. If you focus it by tabbing or automatically, the alert won't occur. Problem is, if you use .focus , alert() steals the focus and then reapplies it in some browsers and you will be stuck in a focus loop. Here's a simple solution:

$(".ss_date_etc input").focus(function () {
   if (!$(this).data('focused')) {
      $(this).data('focused', true);
      alert('focus!');
   }
});

Note that not all browsers will restore focus after an alert, even if you try to force them to. You may want to use some alternative to alert , especially because that would be really annoying to users.

You can also update .data('focused') to false on blur so this happens over again.

You're going at it wrong with your jQuery selector. This should work:

$(".ss_datesel_inp_cont input").focus(function() {
    alert("focused");
});

Also, your input is not set up properly...although "text" is the default input type, you should always specify the type on the input:

<input type="text" autocomplete="off" />

Interestingly enough, your third attempt seemed to work in my test. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM