How can I focus a text input with JavaScript (no jQuery) and make the blinking Cursor/virtual Keyboard on iOS devices appear?
This does not seem to be default behavior when you just call:
element.focus();
Solutions using...
element.click();
element.focus();
... as suggested in other Posts also do not work.
Thanks!
Edit: Demo:
function focusText(){
document.getElementById('text').focus();
}
function focusCalled(){
document.getElementById('text').value = '';
document.getElementById('text').type = 'password';
}
<input type="text" id="text" value="Password" onfocus="focusCalled();">
<button onclick="focusText();">Click me!</button>
I have this problem when clicking my Clear button only in iOS - but only if the value is already clear. The only way I found so far to get the cursor back in code is a hack as follows...
function ClearInput(sInput)
{
var oInput = document.getElementById(sInput);
if (oInput.value.length > 0) oInput.value = '';
else
{
oInput.value = ' ';
setTimeout(function() { ClearInput(sInput); },
gkiMinTOutTms); // gkiMinTOutTms=20
}
oInput.focus();
}
Related
Consider this code:
var input = document.getElementById("hello");
input.addEventListener('blur', function() {
alert('hello');
input.select();
input.focus();
});
<input type="text" value="hello" id="hello" />
The idea around it is to keep the user focused in the input until he/she enters a valid text in it. This is a simplified version of the code.
Js fiddle here: https://jsfiddle.net/wzwft49w/9/
Problem: If you focus on the input and then blur it, you will get an infinite alert popup in Chrome but not in IE.
1. How would you solve this problem?
2. Any ideas on why does this happen?
Notes:
I already checked this question but that fix doesn't work in this case: Other question
Here's an old Chrome bug related to blur and focus (not sure if it could have anything to do with this, although it is marked as solved): Chrome bug
Here is my solution for chrome:
var inputs = document.querySelectorAll("input"),
len = inputs.length,
i;
var gflag=false;
function myalert(m,o) {
if (gflag) {
return;
}
gflag=true;
alert(m);
o.focus();
setTimeout(function() {gflag=false;},10);
}
function makeBlurHandler() {
"use strict";
return function () {
if (this.value === "") {
myalert("Cannot be blank!",this);
this.nextElementSibling.innerHTML = "Cannot be blank!";
} else {
this.nextElementSibling.innerHTML = "";
}
};
}
for (i = 0; i < len; i++) {
inputs[i].addEventListener("blur", makeBlurHandler());
}
.errorMessage {
color: red;
}
<p>
<label for="userName">User Name:</label>
<input type="text" id="userName">
<span class="errorMessage"></span>
</p>
<p>
<label for="passWord">Password:</label>
<input type="text" id="passWord">
<span class="errorMessage"></span>
</p>
it work for IE too, but this not for Firefox due to focus() is not working correctly.
I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});
I created a TextBox :-
TextBox ID="TxtUname" onKeyPress="ENABLE_BTN()"
Now i wrote a function :-
script type="text/javascript"
window.onload = function() {
document.getElementById('SSAccept').disabled = true;
};
function ENABLE_BTN() {
var EN=document.getElementById('TxtUname').value;
if(EN=='') {
document.getElementById('SSAccept').disabled=true;
} else {
document.getElementById('SSAccept').disabled=false;
}
}
</script>
BUT STILL THE DISABLED BUTTON IS NOT GETTING ENABLED ON PRESSING ANY KEY IN THE TEXTBOX.
Can anyone tell me what i did wrong ?? Thanks in Advance
Dev..
onkeypress doesn't work in all browsers -> http://www.quirksmode.org/js/keys.html
onkeyup / onkeydown should be used ->
Working example : http://jsfiddle.net/KCBzk/
HTML :
<input id="TxtUname" value="" onkeydown="ENABLE_BTN()"/><br>
<button id="SSAccept">Some test</button>
Javascript:
window.onload = function() {
document.getElementById('SSAccept').disabled = true;
}
function ENABLE_BTN() {
var EN=document.getElementById('TxtUname').value;
if(EN=='') {
document.getElementById('SSAccept').disabled=true;
} else {
document.getElementById('SSAccept').disabled=false;
}
}
the thing is that you need an event to invoke that function. you should monitor your textbox for change and invoke the function whenever the value changes. like using jquery
$("#TxtUname").keydown(function(e) {
if($("#TxtUname").val == '') {
//..disable button..
} else {
//..enable button
}
});
I have a search box (textbox) and I want to clear it's content when I click inside. (some kind of watermark. Watermark control was not good for me in this case).
I am using "onKeyDown" event to clear the content:
function clearTbSearch(tbSearch) {
if (tbSearch != null && tbSearch.value == '<%= TypeHereText %>') {
tbSearch.value = "";
tbSearch.style.color = "#000000";
}
return true;
}
It works fine in IE and Chrome but in Firefox it takes 3 (!!!) clicks to get it focused. First click does not do anything. The second one clears the textbox but do not focus. The third click get the cursor focused. I tried anything... I would be glad for any suggestions...
Thanks!!!
You can try this to make it look cleaner:
<input type="text" name="myInput" value="Your initial trademark" onfocus="this.value=''" />
No need to use onkeydown event, just use the generic onfocus instead:
var firstTime = true;
window.onload = function() {
var input = document.getElementById("MyInput");
input.onfocus = function() {
if (!firstTime)
clearTbSearch(this);
firstTime = false;
};
input.focus();
};
This way it will work either by keyboard focus or mouse focus e.g. when clicking the textbox.
How can the cursor be focus on a specific input box on page load?
Is it posible to retain initial text value as well and place cursor at end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
There are two parts to your question.
1) How to focus an input on page load?
You can just add the autofocus attribute to the input.
<input id="myinputbox" type="text" autofocus>
However, this might not be supported in all browsers, so we can use javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) How to place cursor at the end of the input text?
Here's a non-jQuery solution with some borrowed code from another SO answer.
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
Here's an example of how I would accomplish this with jQuery.
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
$(document).ready(function() {
$('#id').focus();
});
function focusOnMyInputBox(){
document.getElementById("myinputbox").focus();
}
<body onLoad="focusOnMyInputBox();">
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">
Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
Try:
Javascript Pure:
[elem][n].style.visibility='visible';
[elem][n].focus();
Jquery:
[elem].filter(':visible').focus();
This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
Add this to the top of your js
var input = $('#myinputbox');
input.focus();
Or to html
<script>
var input = $('#myinputbox');
input.focus();
</script>