focus doesn't work in IE - javascript

i have the following function
function change()
{
var input = document.getElementById('pas');
var input2 = input.cloneNode(false);
input2.type = 'password';
input.parentNode.replaceChild(input2,input);
input2.focus();
}
but focus() doesn't work in ie7, so what can i do!
i want to have the cursor inside of input!
thanks
update
great solution, thanks, but now it doesn't work in opera:(

For IE you need to use a settimeout function due to it being lazy, for example:
setTimeout(function() { document.getElementById('myInput').focus(); }, 10);
From http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
For opera, this may help:
how to set focus in required index on textbox for opera
UPDATE:
The following snippet of code handles the case when the element is unavailable and retries after a short period - perfect for slow loading pages and/or elements not available until some time after.
setTimeout(
function( ) {
var el = document.getElementById( "myInput" ) ;
( el != null ) ? el.focus( ) : setTimeout( arguments.callee , 10 ) ;
}
, 10 ) ;

We hit the same issue. For focusing we are using General function which is applying settimeout solution mentioned in:
http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
with 100 milliseconds.
Still on some screens it's not working properly. Especially when iframes are included.
There is another known and similar IE issue:
IE 9 and IE 10 cannot enter text into input text boxes from time to time ->
IE 9 and IE 10 cannot enter text into input text boxes from time to time
What I have noticed is when you have focus, without pointer, you can apply workaround by pressing TAB key (focus on next element) and than SHIFT+TAB which will return to our target element with focus and typing pointer.
In order to be sure we can type inside input we focus on random element and then on our target input.
$('body').focus();
n.focus();
So we applied the same solution in javascript/JQuery in our general focus function.
So there is an if statement
...
if($.browser.msie) {
setTimeout(function() { try {
$('body').focus(); //First focus on random element
$(n).focus(); //Now focus on target element
} catch (e) { /*just ignore */ } }, 100); //See http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
} else { //Standard FF, Chrome, Safari solution...
...
To be sure since there is big regression we are still keeping solution with settimeout as a backup.
Tested on IE10, IE11, Firefox 45, Chrome 49.0.2623.87

IE7 does not support the focus() method. I don't see any method.

I've had the same issue and was able to get IE to work using code behind by making a SetInitialFocus function and calling it in my PageLoad function.
Take a look at the following example and give it a shot, it worked for me.
http://www.cambiaresearch.com/c4/df9f071c-a9eb-4d82-87fc-1a66bdcc068e/Set-Initial-Focus-on-an-aspnet-Page.aspx

function change() {
var input = document.getElementById('pas');
var input2 = input.cloneNode(false);
input2.type = 'password';
input.parentNode.replaceChild(input2, input);
setTimeout(function () {
input2.focus();
}, 10);
}

In Case you are looking to set focus in 1st input element of last row in table.Name of my div where i have kept my table is tableDiv and i am setting focus to last row's 1st inputtext
setTimeout(function(){
$($('#tableDiv tr:last').find('input[type=text]')[0]).focus();
},2);

#Bojan Tadic THANK YOU!
Below Code did the trick :)
$('body').focus(); //First focus on random element
I think the issue comes up when you use input and a placeholder. Managed so solved this thanks to this answer, I was missing that $(body).focus. Made this code to run only on IE so that all my inputs can be freely accessed by 'tabbing'. Previously when I had only tabIndex on my inputs I was able to move to the next one but focus wasn't complete and couldn't write anything in it.
This is complete code.
$('input[name^="someName"]').on('keydown', function(e){
var keyCode = e.which || e.keyCode;
if(keyCode === 9){
e.preventDefault();
$('body').focus();
var nextTabIndex = parseInt($(this).attr("tabIndex"));
nextTabIndex++;
setTimeout(function(){$('input[tabIndex=' + nextTabIndex +']')[0].focus();},20);
}
});

Its is very easy using jQuery, not sure why you are doing it the hard way :)
In this example I have a class assigned to the input field I want the initial focus set called initFocus. You can use any selector you want to find your element. from your code I would use $("#pas").focus();
$(".initFocus").focus();

Related

How to call a function when default browser autocomplete list item selected [duplicate]

I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.

SetInterval in Opera causes select blinking

I need to group tooltips about errors showed by jQuery Validator. So I have written simple loop with setInterval to check if in the same row are more than one input with error class.
setInterval(function() {
$('.xrror').remove();
$('div.row-4:has([name].error)').each(function() {
var tmp = $('[name].error', this);
if(tmp.length > 1) {
$('label.error', this).hide();
tmp.last().parent().append(
$(document.createElement('label')).addClass('error').addClass('xrror').append(
$(document.createElement('span')).text('Fields with errors were marked with red color')
)
);
} else {
$('[name].error', this).parent().find('label.error').show();
}
});
}, 50);
And in Opera it's causing blinking on opened Select element.
Instead of using a setInterval function every 50 miliseconds, which will consume a lot of resources, you should bind your function on events like submit, or change. As it seems to be related to a form validation, you do not need to do anything unless the user modify a field.

How can I set the focus to the next field (based on tabindex) using JavaScript? [duplicate]

In jQuery, how can I trigger the behavior of a user tabbing to the next input field?
I've tried this:
var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);
But triggering the event doesn't move the cursor to the next field.
I suppose I could move the cursor manually using focus(), but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.
Any ideas?
Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/
$.fn.focusNextInputField = function() {
return this.each(function() {
var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
var index = fields.index( this );
if ( index > -1 && ( index + 1 ) < fields.length ) {
fields.eq( index + 1 ).focus();
}
return false;
});
};
The use is as follows:
$( 'current_field_selector' ).focusNextInputField();
See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup event, and check the entered number of characters.
The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus event on the element with that index.
There's a JQuery plugin available:
http://www.mathachew.com/sandbox/jquery-autotab/
Have you tried using
$("input").trigger( 'keypress', e );
as a solution?
I find sometimes being explicit is best.
If that doesn't work possibly even
$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );.
Hope this helps.

Detecting drag drop to HTML textbox?

I have a normal search box on my webpage. It is filled with text: Search this website
This text is removed when you click into the box to type your search query:
onfocus="if(this.value=='Search this website') { this.value=''};
But how can I detect when someone drags text from the page onto the search box, as I often do myself? onfocus is not triggered and the previous text remains.
You need to use the ondrop event, which will only fire if the ondragenter and ondragover events are cancelled. Turns out it's a bit trickier than that because the behavior is different in Firefox than IE, Safari and Chrome.
(function () {
var inp = document.getElementById("test"),
chg = false;
inp.ondragover = inp.ondragenter = function () {
chg = inp.value == "Drop here";
return false;
}
inp.ondrop = function (evt) {
evt = evt || event;
if (chg) {
this.value = evt.dataTransfer.getData("text")
|| evt.dataTransfer.getData("text/plain");
return false;
}
}
})();
Example - Firefox 3+, IE5+, Chrome and Safari. Near as I can tell, Opera doesn't support the event. At least you can get it working for 95% of your visitors though.
Drag Operations - MDC
Have you tried to use the onchange event?
BTW, there is a nifty little jQuery plugin called jquery-defaultvalue which handles all the corner cases for you. If you're using jQuery anyway, it's worth a look.
See - http://www.simplecoding.org/drag-drop-s-ispolzovaniem-html5.html , but page on the russian language (Google Translate would help).

Javascript to make input field in edit mode(insert mode)

How is it possible to make a input field editable in javascript. I mean onFocus putting it in insert mode so that values can be overwritten. Any suggestions ???
This should work in modern browsers (also on mobile):
var input = document.querySelector('input'); // or a textarea
input.addEventListener('keypress', function(){
var s = this.selectionStart;
this.value = this.value.substr(0, s) + this.value.substr(s + 1);
this.selectionEnd = s;
}, false);
jsfiddle
Note: This is a basic form of insert functionality so some default functionality like CTRL+Z may break.
After doing some googling, this seems to be related. It might be working trying the play with the following code a bit, but it might only work in specific browsers on specific operating systems, but it's worth a shot anyway.
document.execCommand('OverWrite', false, true);
document.execCommand('OverWrite', false, false);
As per your request, I would say the implementation would work something like this:
<input type="text"
onFocus="document.execCommand('OverWrite', false, true);"
onBlur="document.execCommand('OverWrite', false, false);">
EDIT: May be totally off-topic, depending on the meaning behind the question.
If you can use jQuery, Jeditable is a nice plugin to do just that.
If you must roll your own code, take a look at how that plugin works and use it as a starting point.
Basically, the steps are:
onFocus/onClick - swap your field with an input.
When the user is "done" (hit Enter, click a button), push the result back to the server via Ajax.
When your request completes, update the interface with the new value, hiding the input.
You can try to mimic Insert mode by rewriting the input value on keyup :
var input = $('input'); // your input element
Event.observe(input, 'keydown', function(e) { // event handler
input._lastvalue = input.value;
});
Event.observe(input, 'keyup', function(e) { // event handler
if(input.value == input._lastvalue) return;
if(input.value.length <= input._lastvalue.length) return;
var caretPos = doGetCaretPosition(input);
input.value = input.value.slice(0,caretPos) + input.value.slice(caretPos+1);
doSetCaretPosition(input, caretPos);
});
Here is a demo : http://jsfiddle.net/z6khW/

Categories

Resources