problem with Chrome form handling: input onfocus="this.select()" - html

I'm using the following HTML code to autoselect some text in a form field when a user clicks on the field:
<input onfocus="this.select()" type="text" value="Search">
This works fine in Firefox and Internet Explorer (the purpose being to use the default text to describe the field to the user, but highlight it so that on click they can just start typing), but I'm having trouble getting it to work in Chrome. When I click the form field in Chrome the text is highlighted for just a split second and then the cursor jumps to the end of the default text and the highlighting goes away.
Any ideas on how to get this working in Chrome as well?

Instead of binding to onfocus event you must bind this action into onclick event and it will work as you wanted.
<input onclick="this.select()" id="txt1" name="txt1" type="text" value="Search">

If you really insist on sticking with onfocus, then you'll need to add onmouseup="return false" too.

This works best for me...
<input type="text" onfocus="this.searchfocus = true;" onmouseup="if(this.searchfocus) {this.select(); this.searchfocus = false;}" />
The mouseup event fires after onfocus.

This is a solution working in Firefox, Chrome and IE, both with keyboard focus and mouse focus. It also handles correctly clicks following the focus (it moves the caret and doesn't reselect the text):
<input
onmousedown="this.clicked = 1;"
onfocus="if (!this.clicked) this.select(); else this.clicked = 2;"
onclick="if (this.clicked == 2) this.select(); this.clicked = 0;"
>
With keyboard focus, only onfocus triggers which selects the text because this.clicked is not set. With mouse focus, onmousedown triggers, then onfocus and then onclick which selects the text in onclick but not in onfocus (Chrome requires this).
Mouse clicks when the field is already focused don't trigger onfocus which results in not selecting anything.

The way I got around this was by creating a wrapper function that uses setTimeout() to delay the actual call to select(). Then I just call that function in the focus event of the textbox. Using setTimeout defers the execution until the call stack is empty again, which would be when the browser has finished processing all the events that happened when you clicked (mousedown, mouseup, click, focus, etc). It's a bit of a hack, but it works.
function selectTextboxContent(textbox)
{
setTimeout(function() { textbox.select(); }, 10);
}
Then you can do something like this to do the selection on focus:
<input onfocus="selectTextboxContent(this);" type="text" value="Search">

Building on Jason's answer, here is a function that replaces the "select" function of DOM input nodes with an updated version that has the timeout built in:
if (/chrome/i.test(navigator.userAgent)) {
HTMLInputElement.prototype.brokenSelectFunction =
HTMLInputElement.prototype.select;
HTMLInputElement.prototype.select = function() {
setTimeout(function(closureThis) { return function() {
closureThis.brokenSelectFunction();
}; }(this), 10);
};
}
Basically, (in Chrome only) we just renamed the built-in but broken select() function to brokenSelectFunction() and then added a new function to all inputs called select() that calls brokenSelectFunction() after a delay. Now, just call select() normally, as the built-in select function has been replaced by the fixed function with Jason's delay suggestion.
This way, you don't have to worry about changing your existing calls to use a wrapper function (and once this is resolved in Chrome, you can just remove the above shim and go back to normal).
textbox.select(); // now runs select with setTimeout built-in (in Chrome only)
Edit: you might want to change the user-agent match from "chrome" to "webkit", as this issue happens in all webkit-browsers including Safari, and this fix will work for any of them.

Just use <input onmouseup=select()>. That works in all browsers.

This question was posted five years ago, but with HTML5, you can make this feature with the placeholder attribute.
<input type="text" name="fname" placeholder="First name">

onfocus="setTimeout(function(){select(this)})"
or onfocus="setTimeout(function(){select(this)},118)" for Firefox.

Thanks ilawton. This works for me
<input type="text" onfocus="this.searchfocus = true;" onmouseup="if(this.searchfocus) {this.select(); this.searchfocus = false;}" />

Related

HTML input type=“file” in Google Chrome not showing popup window

I'm having a problem with the HTML tag <input type="file" /> in Google Chrome.
The 'Browse' button appears on the page as expected, but when I click it in order to select a file, the pop-up dialog window from the browser doesn't open at all.
I 've tested my form and in Firefox and works correct. Any ideas what's wrong and how can I fix it ?
Here is also the code:
<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<label for="imgfile">File input</label>
<input type="file" name="imgfile" />
This happened to me on Chrome v88.0, and I tried everything -- removing all the event handlers, making the simplest form possible, removing all other html and js from the page -- and still the file-selection dialog would not appear when clicking the "Choose File" button.
Then I shut down Chrome and re-opened it ... and it worked again.
Golden advice:
Have you tried turning it off and on again?
In my case the problem was as follows :
Whole document had a "on click handler"
Inside click hander, the code was canceling all propagation with
return false;
Removing this return statement solved problem with input=file.
I knew the problem wasn't an issue with the specific web page I was currently browsing because I went to codepen and tried various file uploaders to no avail.
In my specific scenario, I had run a chrome update a few days ago but failed to relaunch chrome after the update.
Navigating to Help > About Google Chrome, Google had informed me that a relaunch was necessary.
After relaunch, the browser native file picker started appearing again.
There's no reason that this shouldn't work in Chrome. Have you tried copying JUST the mark up in the example you've given us into a HTML file, and opening that? Does it work? It should, unless there's some third party plugin or extension stopping it.
It may be that you have have mark up elsewhere causing this issue; perhaps a layer over the input field catching the click event before it can make it's way down to the "browse" button?
I had the same issue, it would work in safari but not chrome. Turns out I just needed to update my chrome browser. Apparently if your chrome version is out of date by two weeks functionality that has been around for over a decade breaks...you know google engineering at its finest...
There could be two reasons for the input type file not working.
The file type input is styled as visibility: hidden. To hide the input use opacity:0.
There may be click event on document or parent element resisting click on input tag.
I had same issue recently. Restarting chrome fixed it.
Go to chrome://restart to do it.
It seems that a plugin (Colorzila), that I had installed on Chrome, was stopping it. I deactivated it, restart the Chrome and worked eventually.
In my case, vendor css was having a default CSS written to hide the input type file to display: none, as shown below, removing that/overriding that, made browse to work as expected. Hope it may help, that to verify if css for input[type='file'] is driven from other places.
//remove the below code
input[type="file"] {
display: none;
}
I had a similar issue where I was hiding the input element and trying to trigger the popup when a user clicked on the form label.
In my case, the for attribute on the label element didn't match the id of the input. Once I updated the for on the label to match the input's id the popup window worked great.
Simple Example:
<form>
<label for="images">Click here to upload your images!</label>
<input id="images" type="file" accept="images/*" style="display:none;" />
</form>
I found it difficult to style the input itself, so I hid the actual input element and styled the label to look like a file upload input.
Now whenever someone clicks on the label element the file popup will appear even though the input element is hidden.
I set event.preventDefault() in ajax request that is why input value was not being sent in form data
I had a global event event listener on window:
window.addEventListener("click", event => {
event.preventDefault();
event.stopPropagation();
});
Of course this was stopping my input from reacting. Be careful with global or local listeners that do preventDefault()
this worked for me
<input type="file" id="fileProfile2" name="fileProfile2" accept="image/png,image/jpeg" >
You must use it like this
<form enctype="multipart/form-data">
.......
.......
<label for="imgfile">File input</label>
<input type="file" name="imgfile" />
<input type="submit" name="submit" value="submit" />
</form>
Hope it helps someone; in my case the issue was that I had event.preventDefault() applying to the whole document, because I had my eventListener applying to the whole document:
function onMouse( event ) {
event.preventDefault();
// calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouseEventHandler( event );
}
document.addEventListener( 'click', onMouse, false );
I only wanted my custom event handlers to apply to one div, not to the whole document, and specifically I didn't want my event handlers overriding the form events, set up in another div. So I limited the scope of my eventListeners to the 'visualizationContainer' div:
document.getElementByID('visualizationContainer').addEventListener( 'click', onMouse, false );
That fixed everything.
Observed Symptoms: The "Choose File" button (from the input type=file html tag) does not pop a file selection dialog. Same web page works on Firefox (version 68.5.0) on the same device.
Answer: Use Firefox on Android if the failure to select a file for upload symptoms appear. The code below does work on Linux Chrome (version 80.0.3987.87). It also works on Windows 10 Chrome (version 80.0.3987.122). This seems to only apply to Android and likely only certain versions.
Hardware: LG-H812
Android version: 6.0
Chrome version: 80.0.3987.117
Code:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>t9.php</title>
</head>
<body>
<h1>t9.php</h1>
<form method='post' enctype='multipart/form-data'>
<input type='file' name='filename'/><br>
<br>
<input type='submit' name='submit' value='submit'/><br>
<br>
</form>
</body>
</html>

Knockout binding not updating after dragging the text with mouse in firefox

I have one simple textbox and span binded with the knockout observable like this
function ViewModel(){
var self=this;
self.name=ko.observable();
}
and
<input type="text" data-bind="value: name"/>
<br/>
<h1 data-bind="text: name"></h1>
<h2>dragdata</h2>
here is the fiddle for this http://jsbin.com/UqugasE/3/edit
Now when I drag some text from some source and put it into the textbox and lose focus the binding is updating only in Chrome and Ie9+, but it is not working in firefox(25.0)..
I think that in firefox the value is only updating after user have key interaction with the input box and lose focus..
Any idea or solution for this..
P.S
I can update the value of the binding with
valueUpdate:'input'
but I just wanted to know the reason why it is not working with firefox.
It seems to be a know bug :
https://github.com/knockout/knockout/issues/683
It's caused by FF does'nt support values update event (change event) like others.
As you said, you can do it with the valueUpdate databindingHandlers.
<input type="text" data-bind="value: name, valueUpdate:'input'"/>

Knockout JS: Change event not firing for HTML5 date on iPad

I am using Knockout JS library to bind the HTML5 input controls in my Web application which is intended to run on iPad (iOS5, Safari 5.1). The binding works fine for the input types like text and select but not for date. After selecting a date value through the datepicker the value is not getting bound to the viewModel property (in effect not getting saved).
This is how my HTML looks.
<input id="dob" name="dob" type="date" data-bind="value: dob" />
I tried to work around with a custom binding where I initialized a change event handler.
ko.bindingHandlers.datePicker = {
init: function (element, valueAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).val());
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(value);
}
};
Changing the HTML code to -
<input id="dob" name="dob" type="date" data-bind="datePicker: dob" />
Strangely, even that event is not firing. Please note that in both of the scenarios the binding happens perfectly in Windows XP on Opera and Safari browsers.
Ultimately, I got the solution to my problem by using the 'blur' event instead of 'change' in the custom binding. Now the event handler is being called and I am manually setting the value from the date control.
Now my question is, is it something that I am not doing correctly and if not then why doesn't the change event of the HTML5 date control not fire, whether by default or through custom binding? I want the date control to work as it is supposed to.
You are not doing anything wrong from a Knockout perspective. Those events really just are not fired (without Knockout even in the picture) from what I can tell by testing and by researching it a bit.
You can avoid a custom binding by doing:
<input type="date" data-bind="value: myDate, valueUpdate: 'blur'" />
I had similar issue, but in my case, even the blur event is actually not fired. So I used input event with valueUpdate property, and resolved the problem.

Remove text caret/pointer from focused readonly input

I am using an <input readonly="readonly">, styled as normal text to remove the appearance of an interactive field, but still display the value.
This is very useful to prevent a user from editing a field, while still being able to post the value. I realize this is a convenience method and that there are several workarounds, but I want to use this method.
Problem: The blinking caret still appears when the field is clicked/focused. (At least in FF and IE8 on Win7)
Ideally, I would like it to behave as it normally does, focusable, but without the blinking caret.
Javascript solutions welcome.
On mine there is no caret or so:
<input type="text" value="test" readonly="readonly" >
Take a look at this: http://www.cs.tut.fi/~jkorpela/forms/readonly.html
Sorry, now I understand your problem.
Try this:
<input type="text" value="test" onfocus="this.blur()" readonly="readonly" >
You can use this in your css, but it will not focus:
[readonly='readonly'] {
pointer-events: none;
}
You can remove the blinking caret by specify the css attribute into transparent
caret-color: transparent;
you can test the result here
It can be done using html and javascript
<input type="text" onfocus="this.blur()" readonly >
or jQuery
$(document).on('focus', 'input[readonly]', function () {
this.blur();
});
the only way i found for this was
//FIREFOX
$('INPUT_SELECTOR').focus(function () {
$(this).blur();
});
//INTERNET EXPLORER
$('INPUT_SELECTOR').attr('unselectable', 'on');
KENDO
$('.k-ff .k-combobox>span>.k-input').focus(function () {
$(this).blur();
});
$('.k-ie .k-combobox>span>.k-input').attr('unselectable', 'on');
The onfocus/blur method works ok to remove the cursor from a readonly field, but the browser does not automatically refocus on the next field, and you may lose focus altogether, which is not what the user usually expects. So, if this is required, you can use plain javascript to focus on the next field you want, but you have to specify the next field:
<input type="text" name="readonly-field" value="read-only"
readonly onfocus="this.form.NextField.focus()">
Where 'NextField' is the name of the field to goto. (Alternatively, you could provide some other means to locate the next field). Obviously, this is more involved if you want to navigate to some non-visible UI element, like a tab-panel, as you will need to arrange this as well.
Easy!
Just add disabled to input and it will not be clickable (focused)

Preventing Firefox from remembering the input value on refresh with a meta tag

When I refresh a page with Firefox, the values of the check boxes, input fields, etc. are kept.
Is there a way to make Firefox not keep them, using a meta tag without JavaScript?
For an input tag there's the attribute autocomplete you can set:
<input type="text" autocomplete="off" />
You can use autocomplete for a form too.
If you want to prevent remembering field values after reload, while still getting to use autocomplete:
First define autocomplete off in the markup:
<input id="the-input" type="text" autocomplete="off" />
Then re-enable autocomplete programatically:
document.getElementById('the-input').autocomplete = 'on';
this will disable autocomplete just at the right time when the page loads and re-enable it so it can be used (but the field value will be empty as it should).
If it does not work for you, try wrapping the js code in a setTimeout or requestAnimationFrame.
// Internet Explorer fix - do this at the end of the page
var oninit_async_reset = setInterval(function() { resetFormIEFix(); }, 500);
function resetFormIEFix() {
$('#inputid').val('');
if (typeof oninit_async_reset != 'undefined')
clearInterval(oninit_async_reset);
}