Hello I am working on a simple form that also uses place-holder text. I am implementing this behaviour with JQuery and not html attributes, mainly because the place-holder input also shows error messages to the user which need to be styled differently than plain place-holder text.
Right now the form behaves like this.
Now this is all fine, but when the user presses the TAB key to change focus, none of the above happens.
Here is the relevant JQuery code and the HTML:
$("#plh_username").click(function(){ $(this).hide(); $("#username").focus(); }); $('body').click(function(e){ var target = $(e.target); if(!target.is('#plh_username')) { if ( $("#username").val() == "" ){ $("#plh_username").show(); } } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="input" id="plh_username" class="inp_placeholder" value="Username" /> <input type="text" name="username" id="username" value="" />
How can I achieve the same effect when the user selects an input field without actually clicking on one?
You could try using .focus()
and .focusout()
instead of .click()
.
$("#plh_username").focus(function(){ $(this).hide(); $("#username").focus(); }); $('#username').focusout(function(){ if ($(this).val() === ""){ $("#plh_username").show(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="input" id="plh_username" class="inp_placeholder" value="Username" /> <input type="text" name="username" id="username" value="" /> <input value="Press tab or shift+tab" />
Quote from the documentation :
Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events.
Dont use .click()
. Use .focus()
.
I think you are looking for onfocus event. This event triggers when a control gains the focus.
$("#plh_username").focus( function(){
alert("focus")
});
for example see http://jsfiddle.net/wb2vef0g/
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.