Chrome: Blur - Alert - Focus sequence causes infinite alert loop - javascript

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.

Related

JavaScript: input.focus() and show Cursor

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();
}

Internet explorer 9 jquery error when trying to select a button

I'm trying to make a button to work in my HYML + javascript + jquery code, but IE9 fails, chrome and firefox works good.
I'm using jQuery 2.1.1, so IE9 is supported. In my own code $("#myButton").click(function (e) {}); does not even get called on click.
I'm making a button with <input type="button" id="myButtonID"/> or with <input id="myButton" type="submit" value="someValue" class="success radius button" />, and I'm getting error at this.select() line in the following dynamically generated code.
var clicked = false;
$("input,textarea").click(function () {
var length = document.getSelection().toString().length;
if (length > 0) {
event.preventDefault();
document.selection.empty();
}
else {
if (!clicked) {
this.select();
clicked = true;
}
}
});
Any ideas what should i do to solve this issue?

Disabling BACKSPACE in chrome

I have an input field for mobile numbers and i want that inside that input field "+91" should be visible to the user all the time.. means he can not erase it.
So i planned to disable BACKSPACE and DELETE button when the value of INPUT FIELD is equal to +91
The startegy is working fine for me in FIREFOX but its all screwed up in CHROME.
I googled a lot but couldnt find any successfull code for Disabling Backspace in CHROME. :(
Here is my code for FIREFOX
<script language="JavaScript" type="text/javascript">
document.onkeypress = function(e) // FireFox/Others
{
var t=e.target.id;
var kc=e.keyCode;
if ((kc == 8 || kc == 46) && t == "phonen" && document.getElementById(t).value=="+91")
{ e.preventDefault();
return false;}
else {
return true
}
}
function sett(e)
{e.value="+91";}
</script>
Can anyone suggest me how can i do the same in CHROME???
As I wrote in a comment... Don't even bother with this kind of approach. Just fake it. Here's a simple way (though you might want to adjust fonts, spacing, etc.):
html:
<div class="prefix-wrapper">
<span class="prefix">+91</span>
<input type="text" value="">
</div>
css:
.prefix-wrapper {
position: relative;
}
.prefix-wrapper .prefix {
position: absolute;
z-index: 2;
top: 3px;
left: 5px;
color: #999;
}
input {
padding-left: 30px;
}
demo: http://jsbin.com/elatot/1/
User still can click with a mouse or move the cursor and edit +91 strings.
I would suggest that you bind .keyup and .change handlers to your input and check then if it contains your prefix(note that jQuery would be it much easier). Like this:
$('#your_input_id').on('keyup change', function() {
if ( $(this).val().indexof('+91') != 0) $(this).val('+91');
});
A solution not using jQuery would be to hook up to the change/keyup events directly:
var checkPhone = function (e) {
if (e.target.value.indexOf('+91') != 0) {
e.target.value = '+91';
}
}
var phoneElement = document.getElementById('phonen');
phoneElement.onchange = checkPhone;
phoneElement.onkeyup = checkPhone;
Try this with jQuery:
// HTML Code
<input type="text" name="phone" id="phone" class='phone' placeholder='+918888888888' value='' maxlength='13' />
// jQuery code
$(document).keydown(function (e) {
var l = $('.phone').val().length;
var elid = $(document.activeElement).hasClass('phone');
if (e.keyCode === 8 && elid && l == 3) {
return false;
} else {
return true;
}
});
Fiddle DEMO

How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8

I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.
<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
Javascript:
function enterToTab(myEvent) {
if (myEvent.keyCode == 13) {
myEvent.keyCode = 9;
}
}
function changeEvent(myInput) { var test = "hello"; }
In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)
Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?
Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.
Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.
UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?
Looks like IE9 events are immutable. Once they've been fired you can't change the properties on them, just preventDefault() or cancel them. So you best option is to cancel any "enter" events and re-dispatch a new DOM event from the text input.
Example
function enterToTab(event){
if(event.keyCode == 13){
var keyEvent = document.createEvent("Event");
// This is a lovely method signature
keyEvent.initKeyboardEvent("onkeydown", true, true, window, 9, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(keyEvent);
// you may want to prevent default here
}
}
Here's the MSDN documentation around IE9 DOM events:
Event Object - http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
createEvent - http://msdn.microsoft.com/en-us/library/ff975304(v=vs.85).aspx
initialize a Keyboard Event - http://msdn.microsoft.com/en-us/library/ff975297(v=vs.85).aspx
Here is a different idea; change the on submit so that it calls a function instead of processing the form. in the function check all the fields to see if they are blank, then focus on the next field that doesn't have a value.
So they type a value into field 1, hit enter, and the function runs. it sees that field 1 is full, but field 2 isn't, so focus on field 2.
Then when all the fields are full, submit the form for processing.
If the form has fields that can be blank, you could use a boolean array that would keep track of which fields received focus using the onfocus() event.
Just an outside the box idea.
The previous IE-version allowed the non standard writable event.keyCode property, IE9 now conforms to the standards.
You may want to consider the functionality you are after: you want to make the enter key behave like the tab key, i.e. moving the focus to the next (text) input field. There are more ways to do that. One of them is using the tabindex attribute of the text input fields. If you order the fields in your form using this tabindex attribute, the functions I present here may yield the same result as your previous keyCode method. Here are two functions I tested in this jsfiddle. An (text) input field now looks like:
<input type="text"
onkeypress="nextOnEnter(this,event);"
name="" value=""
tabindex="1"/>
the functions to use for tabbing:
function nextOnEnter(obj,e){
e = e || event;
// we are storing all input fields with tabindex attribute in
// a 'static' field of this function using the external function
// getTabbableFields
nextOnEnter.fields = nextOnEnter.fields || getTabbableFields();
if (e.keyCode === 13) {
// first, prevent default behavior for enter key (submit)
if (e.preventDefault){
e.preventDefault();
} else if (e.stopPropagation){
e.stopPropagation();
} else {
e.returnValue = false;
}
// determine current tabindex
var tabi = parseInt(obj.getAttribute('tabindex'),10);
// focus to next tabindex in line
if ( tabi+1 < nextOnEnter.fields.length ){
nextOnEnter.fields[tabi+1].focus();
}
}
}
// returns an array containing all input text/submit fields with a
// tabindex attribute, in the order of the tabindex values
function getTabbableFields(){
var ret = [],
inpts = document.getElementsByTagName('input'),
i = inpts.length;
while (i--){
var tabi = parseInt(inpts[i].getAttribute('tabindex'),10),
txtType = inpts[i].getAttribute('type');
// [txtType] could be used to filter out input fields that you
// don't want to be 'tabbable'
ret[tabi] = inpts[i];
}
return ret;
}
If you don't want to use tabindex and all your input fields are 'tabbable', see this jsfiddle
[EDIT] edited functions (see jsfiddles) to make use of event delegation and make it all work in Opera too. And this version imitates shift-TAB too.
The code above causes problems. Here's some code that will help you. Works on IE9, FF5 etc.
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
And then you should just create your input texts or whatever
<input type="text" id="1" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="2" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="3" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="4" onkeydown="return tabOnEnter(this,event)"/>
A <button> element on a page will cause this problem.
In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.
<button type="button">Click me!</button>
Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.
Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE problem with Enter key and <button> elements</title>
</head>
<body>
<script>
function press(event) {
if (event.keyCode == 13) {
document.getElementById('input2').focus();
// In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
// event.preventDefault && event.preventDefault();
}
}
</script>
<input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
<input id="input2" type="text" value="input2. Press enter here." /><br />
<input id="button1" type="button" value='I am an <input type="button">' /><br />
<button id="button2" type="button">I am a <button type="button"></button><br />
<button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
Mike Fdz's code is superb. In order to skip over hidden fields, you may want to change the line
return form.elements[++e % form.elements.length];
to this:
e++;
while (form.elements[e % form.elements.length].type == "hidden") {
e++;
}
return form.elements[e % form.elements.length];
Use onpaste along with onkeypress like
Consider you have wrriten a javascript function which checks the text lenght so we will need to validate it on key press like as below
<asp:TextBox ID="txtInputText" runat="server" Text="Please enter some text" onpaste="return textboxMultilineMaxNumber(this,1000);" onkeypress="return textboxMultilineMaxNumber(this,1000);"></asp:TextBox>
onkeypress will work in both FF and IE
but if you try to do ctr+V in textbox then onpaste will handle in IE in FF onkeypress takes care of it
This is what I have done with what I found over the internet :
function stopRKey(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio")))
{
getNextElement(node).focus();
return false;
}
}
function getNextElement(field)
{
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
e++;
while (form.elements[e % form.elements.length].type == "hidden")
{
e++;
}
return form.elements[e % form.elements.length];;
}
To prevent a "submit event" triggered by Enter-Keyboard in your Form in IE9, retire any button inside the form area. Place him (button) in outside of form's area.
function enterAsTab() {
var keyPressed = event.keyCode; // get the Key that is pressed
if (keyPressed == 13)
{
//case the KeyPressed is the [Enter]
var inputs = $('input'); // storage a array of Inputs
var a = inputs.index(document.activeElement);
//get the Index of Active Element Input inside the Inputs(array)
if (inputs[a + 1] !== null)
{
// case the next index of array is not null
var nextBox = inputs[a + 1];
nextBox.focus(); // Focus the next input element. Make him an Active Element
event.preventDefault();
}
return false;
}
else {return keyPressed;}
}
<HTML>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onKeyPress="return enterAsTab();">
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
</body>
</HTML>

Focus Input Box On Load

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>

Categories

Resources