activate readonly back after editing the input jquery - javascript

how can i activate the readonly back after finishing the edit of the input ?
this is my code for now :
<script type="text/javascript">
$(document).ready(function () {
$("input").bind('click focus', function(){
$('input').each(function(){
$(this).attr("readonly", false);
});
});
});
</script>
an input like this :
<input type="text" class="m" readonly="readonly" id="anchor_text">
i think something with focusout, i need to put readonly back when i go to the next input, so the edited input can't be change unless i hit again click on it.

try:
$("input").bind('click focus', function(){
$(this).attr("readonly", false);
}).bind('blur', function(){
$(this).attr("readonly", true);
});​
demo : http://jsfiddle.net/DkCvu/1/

I'm sorry, but I'm struggling to see the point of this. If I get this right, you want the input field not to be editable until it is clicked or selected by the user (which is basically how input fields work anyhow: you can't change their value unless you select them). After these input fields loose their focus, they should go back to being read only. If this is the case, you're over complicating things. However, that is none of my business. The best way to get this done IMO, is by delegating the event.
I therefore put together a couple of fiddles, on pure JS, on jQuery. Both are far from perfect, but should help you on your way.
Regular JS (fiddle here):
var dv = document.getElementById('inputDiv');
if (!dv.addEventListener)
{
dv.attachEvent('onfocusin',switchRO);
dv.attachEvent('onfocusout',switchRO);
}
else
{
dv.addEventListener('focus',switchRO,true);
dv.addEventListener('blur',switchRO,true);
}
function switchRO (e)
{
var self;
e = e || window.event;
self = e.target || e.srcElement;
if (self.tagName.toLowerCase() === 'input')
{
switch (e.type)
{
case 'onfocusin':
case 'focus':
self.removeAttribute('readonly');
break;
default:
self.setAttribute('readonly','readonly');
}
}
return true;
}
In jQuery, this might look something like this (jQuery with .on, jsfiddle here):
$('#inputDiv input').on(
{
focus: function()
{
$(this).removeAttr('readonly');
},
blur: function()
{
$(this).attr('readonly','readonly');
}
});
​
I posted both jQuery and pure JS, because I find it both informative and educational to know what goes on behind the screens in jQuery.

Related

e.preventDefault() behvaing differently

I have a very simple jQuery UI spinner as follows:
<input value="2" class="form-control ui-spinner-input" id="spinner" aria-valuemin="2" aria-valuemax="24" aria-valuenow="2" autocomplete="off" role="spinbutton" type="text">
Using jQuery I set the above text box readonly true/false. The readonly and value is set based on the checkbox a user selects and that function looks like
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
var isChecked = this.checked;
var currentElement = this;
var $radioButton = $('.usage-failure-type-radio');
$targetCheckBoxes.filter(function () {
return this.id !== currentElement.id;
}).prop('disabled', isChecked);
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked);
$radioButton.first().prop('checked', isChecked);
$radioButton.not(':checked').toggle(!isChecked).parent('label').toggle(!isChecked);
$('.usage-before-failure > div > span.ui-spinner > a').toggle(!isChecked);
});
}
Now what I'm trying to achieve is when the #spinner input is readonly and if the user presses the back space I want to prevent the default behaviour e.g. do navigate away from the page. For this I thought I'd do the following:
$('.prevent-default').keydown(function (e) {
e.preventDefault();
});
Which works fine if the input has the class prevent-default on page load. However, if I add it in my checkBoxes function in the following line
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default')
Then I press the backspace it ignores e.prevenDefault();
But if I do
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).keydown(function (e) { e.preventDefault(); });
Then it works absolutely fine.
Can someone tell me why this is happening please.
The reason I want to use a separate function with a class name is because I have various inputs which get set to read only based on different check/radio values.
Can someone tell me why this is happening please
This is because of the DOM parser and the timing when JavaScript is executed.
If you already have an element with a class prevent-default in your DOM before JS is executed, then the JavaScript will recognise and handle it correctly. If you instead add the class afterwards with JS, then you have to re-initialise the keydown-event again to make it work.
To re-initialise you will need something like this:
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
...
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default');
// assign new keydown events
handleKeyDown();
...
});
}
function handleKeyDown() {
// release all keydown events
$('#spinner').off( "keydown", "**" );
$('.prevent-default').keydown(function (e) {
e.preventDefault();
// do more stuff...
});
}

Issues displaying a dynamically updated HTML input value

I'm struggling to get the behaviour I need - as follows:
A HTML form is pre-populated with a value via jQuery. When the user focuses on the input field I want the form to clear. On blur from the form, the form should repopulate the form with the existing value.
I have a solution that clears and repopulates the form but it fails as soon as anything is typed in.
This is what I have so far:
var x = "Default";
$(function () {
$("input").attr({
"value": x
});
$("input").focus(function () {
$("input").attr({
"value": ""
});
});
$("input").blur(function () {
$("input").attr({
"value": x
});
});
});
https://jsfiddle.net/thepeted/p74kfdt8/6/
If I look in developer tools, I can see the input value is changing dynamically in the DOM, but in the case that the user has typed something in to the form, the display no longer updates.
I'd love to understand why this is happening (ie, why it works in one case and not the other). Also, if there is a better way of approaching the problem.
As pointed out by Stijn, best practice would be to use the placeholder attibute.
However if you do want to use a function for it. I would check on the focus if the value is the default value or not. If so, empty the input, if not, don't do anything.
On blur, you also only want to place the default value back if the value is empty... so check for that aswell.
var x = "Default";
$(function() {
$('input[type=text]').val(x);
$('input[type=text]').on('focus', function() {
var elem = $(this);
if (elem.val() == x)
elem.val('');
}).on("blur", function() {
var elem = $(this);
if (elem.val() == '')
elem.val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Your edited jsfiddle.
updated code:
$("input").blur(function () {
$("input").val(x);
});
Personnaly, I'd use the placeholder attribute as everyone pointed out. If you too are facing the need to support older browsers and some others that do not support the placeholder attribute, use this snippet I've made:
$('input[placeholder]').each(function(){
var $this = $(this);
$this.val($this.attr('placeholder')).css('color','888888');
$this.focus(function(){
if($(this).val() == $(this).attr('placeholder'))
$(this).val('').css('color','');
});
$this.blur(function(){
if($(this).val() == '')
$(this).val($(this).attr('placeholder')).css('color','888888');
});
});
This script will find all inputs with a placeholder attribute, give it's value to the input, and add the correct events. I've left the css calls just to show you where to put the codes to mimic the greyed text like modern browsers do.
Try this code
var x = "Default";
$(function () {
$("input").val(x);
$("input").focus(function () {
$("input").val("");
});
$("input").blur(function () {
$("input").val(x);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>

Jquery - Differentiate between 'click' and 'focus' on same input when using both

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.
The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:
HTML:
<body>
<input type="textbox" name="tb1" class="input1"></input>
<label> box 1 </label>
<input type="textbox" name="tb2" class="input2"></input>
<label> box 2 </label>
</body>
JQuery
$(function () {
$('.input2').click(function() {
alert("click");
});
$('.input2').focus(function() {
alert("focus");
});
});
JSFiddle: http://jsfiddle.net/XALSn/2/
You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.
Thanks in advance for any advice.
How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.
I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:
$(function () {
$('.input2').on("click focus blur", function(e) {
e.stopPropagation();
if(e.type=="click"){
if($(this).data("justfocussed")){
$(this).data("justfocussed",false);
} else {
//I have been clicked on whilst in focus
console.log("click");
}
} else if(e.type=="focus"){
//I have been focussed on (either by clicking on whilst blurred or by tabbing to)
console.log("focus");
$(this).data("justfocussed",true);
} else {
//I no longer have focus
console.log("blur");
$(this).data("justfocussed",false);
}
});
});
http://jsfiddle.net/XALSn/12/
This probably won't be the best answer, but this is a way of doing it. I would suggest adding tab indexes to your inputs and firing the focus event when you blur from another input.
I've added that to this fiddle:
http://jsfiddle.net/XALSn/9/
$(function () {
$('.input2').click(function(e) {
alert("click");
e.preventDefault();
});
});
$('input').blur(function(){
$('input').focus(function() {
alert("focus");
});
});
You can use one thing I am using very often in JS
var doSomething = true;
$(function () {
$('.input2').click(function(e) {
if (doSomething) {
// do something :)
}
doSomething = false;
});
$('.input2').focus(function() {
if (doSomething) {
// do something :)
}
doSomething = false;
});
});
But You have to change value of doSomething on mouseout or foucs over etc. :)
$(function () {
var hasFocus = false;
$("body")
.off()
.on({
click : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("click");
}
},
focus : function()
{
if(!hasFocus)
{
hasFocus = true;
alert("focus");
}
}
},".input2");
});
try setting a flag hasFocus and act accordingly
http://jsfiddle.net/AEVTQ/2/
just add e.preventDefault() on the click event
$(function () {
$('.input2').click(function(e) {
console.log("click");
e.preventDefault();
e.stopPropagation();
});
$('.input2').focus(function() {
console.log("focus");
});
});
If I understand your question right, the e.prevnetDefault() will prevent the browser from automatically focusing on click. Then you can do something different with the click than would with the focus

Submit jQuery UI dialog on <Enter>

I have a jQuery UI dialog box with a form. I would like to simulate a click on one of the dialog's buttons so you don't have to use the mouse or tab over to it. In other words, I want it to act like a regular GUI dialog box where simulates hitting the "OK" button.
I assume this might be a simple option with the dialog, but I can't find it in the jQuery UI documentation. I could bind each form input with keyup() but didn't know if there was a simpler/cleaner way. Thanks.
I don't know if there's an option in the jQuery UI widget, but you could simply bind the keypress event to the div that contains your dialog...
$('#DialogTag').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
//Close dialog and/or submit here...
}
});
This'll run no matter what element has the focus in your dialog, which may or may not be a good thing depending on what you want.
If you want to make this the default functionality, you can add this piece of code:
// jqueryui defaults
$.extend($.ui.dialog.prototype.options, {
create: function() {
var $this = $(this);
// focus first button and bind enter to it
$this.parent().find('.ui-dialog-buttonpane button:first').focus();
$this.keypress(function(e) {
if( e.keyCode == $.ui.keyCode.ENTER ) {
$this.parent().find('.ui-dialog-buttonpane button:first').click();
return false;
}
});
}
});
Here's a more detailed view of what it would look like:
$( "#dialog-form" ).dialog({
buttons: { … },
open: function() {
$("#dialog-form").keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).parent().find("button:eq(0)").trigger("click");
}
});
};
});
I have summed up the answers above & added important stuff
$(document).delegate('.ui-dialog', 'keyup', function(e) {
var target = e.target;
var tagName = target.tagName.toLowerCase();
tagName = (tagName === 'input' && target.type === 'button')
? 'button'
: tagName;
isClickableTag = tagName !== 'textarea' &&
tagName !== 'select' &&
tagName !== 'button';
if (e.which === $.ui.keyCode.ENTER && isClickableTag) {
$(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
return false;
}
});
Advantages:
Disallow enter key on non compatible elements like textarea , select , button or inputs with type button , imagine user clicking enter on textarea and get the form submitted instead of getting new line!
The binding is done once , avoid using the dialog 'open' callback to bind enter key to avoid binding the same function again and again each time the dialog is 'open'ed
Avoid changing existing code as some answers above suggest
Use 'delegate' instead of the deprecated 'live' & avoid using the new 'on' method to allow working with older versions of jquery
Because we use delegate , that mean the code above can be written even before initializing dialog. you can also put it in head tag even without $(document).ready
Also delegate will bind only one handler to document and will not bind handler to each dialog as in some code above , for more efficiency
Works even with dynamically generated dialogs like $('<div><input type="text"/></div>').dialog({buttons: .});
Worked with ie 7/8/9!
Avoid using the slow selector :first
Avoid using hacks like in answers here to make a hidden submit button
Disadvantages:
Run the first button as the default one , you can choose another button with eq() or call a function inside the if statement
All of dialogs will have same behavior you can filter it by making your selector more specific ie '#dialog' instead of '.ui-dialog'
I know the question is old but I have had the same need, so, I shared the solution I've used.
$('#dialogBox').dialog('open');
$('.ui-dialog-buttonpane > button:last').focus();
It works beautifully with the latest version of JQuery UI (1.8.1).
You may also use :first instead of :last depending on which button you want to set as the default.
This solution, compared to the selected one above, has the advantage of showing which button is the default one for the user. The user can also TAB between buttons and pressing ENTER will click the button currently under focus.
Cheers.
Ben Clayton's is the neatest and shortest and it can be placed at the top of your index page before any jquery dialogs have been initialized. However, i'd like to point out that ".live" has been deprecated. The preferred action is now ".on". If you want ".on" to function like ".live", you'll have to use delegated events to attach the event handler. Also, a few other things...
I prefer to use the ui.keycode.ENTER method to test for the enter
key since you don't have to remember the actual key code.
Using "$('.ui-dialog-buttonpane button:first', $(this))" for the
click selector makes the whole method generic.
You want to add "return false;" to prevent default and stop
propagation.
In this case...
$('body').on('keypress', '.ui-dialog', function(event) {
if (event.keyCode === $.ui.keyCode.ENTER) {
$('.ui-dialog-buttonpane button:first', $(this)).click();
return false;
}
});
A crude but effective way to make this work more generically:
$.fn.dlg = function(options) {
return this.each(function() {
$(this).dialog(options);
$(this).keyup(function(e){
if (e.keyCode == 13) {
$('.ui-dialog').find('button:first').trigger('click');
}
});
});
}
Then when you create a new dialog you can do this:
$('#a-dialog').mydlg({...options...})
And use it like a normal jquery dialog thereafter:
$('#a-dialog').dialog('close')
There are ways to improve that to make it work in more special cases. With the above code it will automatically pick the first button in the dialog as the button to trigger when enter is hit. Also it assumes that there is only one active dialog at any given time which may not be the case. But you get the idea.
Note: As mentioned above, the button that is pressed on enter is dependent on your setup. So, in some cases you would want to use the :first selector in .find method and in others you may want to use the :last selector.
Rather than listening for key codes like in this answer (which I couldn't get to work) you can bind to the submit event of the form within the dialog and then do this:
$("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();
So, the whole thing would look like this
$("#my_form").dialog({
open: function(){
//Clear out any old bindings
$("#my_form").unbind('submit');
$("#my_form").submit(function(){
//simulate click on create button
$("#my_form").parents('.ui-dialog').first().find('.ui-button').first().click();
return false;
});
},
buttons: {
'Create': function() {
//Do something
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
Note that different browsers handle the enter key differently, and some do not always do a submit on enter.
I don't know about simpler, but ordinarily you would track which button has the current focus. If the focus is changed to a different control, then the "button focus" would remain on the button that had focus last. Ordinarily, the "button focus" would start on your default button. Tabbing to a different button would change the "button focus". You'd have to decide if navigating to a different form element would reset the "button focus" to the default button again. You'll also probably need some visual indicator other than the browser default to indicate the focused button as it loses the real focus in the window.
Once you have the button focus logic down and implemented, then I would probably add a key handler to the dialog itself and have it invoke the action associated with the currently "focused" button.
EDIT: I'm making the assumption that you want to be able hit enter anytime you are filling out form elements and have the "current" button action take precedence. If you only want this behavior when the button is actually focused, my answer is too complicated.
I found this solution, it work's on IE8, Chrome 23.0 and Firefox 16.0
It's based on Robert Schmidt comment.
$("#id_dialog").dialog({
buttons: [{
text: "Accept",
click: function() {
// My function
},
id: 'dialog_accept_button'
}]
}).keyup(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER)
$('#dialog_accept_button').click();
});
I hope it help anyone.
Sometimes we forget the fundamental of what the browser already supports:
<input type="submit" style="visibility:hidden" />
This will cause the ENTER key to submit the form.
I did such way... ;) Hope it will helpful for somebody..
$(window).keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(".ui-dialog:visible").find('.ui-dialog-buttonpane').find('button:first').click();
return false;
}
});
This should work to trigger the click of the button's click handler. this example assumes you have already set up the form in the dialog to use the jquery.validate plugin. but could be easily adapted.
open: function(e,ui) {
$(this).keyup(function(e) {
if (e.keyCode == 13) {
$('.ui-dialog-buttonpane button:last').trigger('click');
}
});
},
buttons: {
"Submit Form" : function() {
var isValid = $('#yourFormsID').valid();
// if valid do ajax call
if(isValid){
//do your ajax call here. with serialize form or something...
}
}
I realise there are a lot of answers already, but I reckon naturally that my solution is the neatest, and possibly the shortest. It has the advantage that it works on any dialogs created any time in the future.
$(".ui-dialog").live("keyup", function(e) {
if (e.keyCode === 13) {
$('.ok-button', $(this) ).first().click();
}
});
Here is what I did:
myForm.dialog({
"ok": function(){
...blah...
}
Cancel: function(){
...blah...
}
}).keyup(function(e){
if( e.keyCode == 13 ){
$(this).parent().find('button:nth-child(1)').trigger("click");
}
});
In this case, myForm is a jQuery object containing the form's html (note, there aren't any "form" tags in there... if you put those in the whole screen will refresh when you press "enter").
Whenever the user presses "enter" from within the form it will be the equivalent of clicking the "ok" button.
This also avoids the issue of having the form open with the "ok" button already highlighted. While that would be good for forms with no fields, if you need the user to fill in stuff, then you probably want the first field to be highlighted.
done and done
$('#login input').keyup(function(e) {
if (e.keyCode == 13) {
$('#login form').submit();
}
}
if you know the button element selector :
$('#dialogBox').dialog('open');
$('#okButton').focus();
Should do the trick for you. This will focus the ok button, and enter will 'click' it, as you would expect. This is the same technique used in native UI dialogs.
$("#LogOn").dialog({
modal: true,
autoOpen: false,
title: 'Please Log On',
width: 370,
height: 260,
buttons: { "Log On": function () { alert('Hello world'); } },
open: function() { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();}
});
I found a quite simple solution for this problem:
var d = $('<div title="My dialog form"><input /></div>').dialog(
buttons: [{
text: "Ok",
click: function(){
// do something
alert('it works');
},
className: 'dialog_default_button'
}]
});
$(d).find('input').keypress(function(e){
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
e.preventDefault();
$('.dialog_default_button').click();
}
});
$('#DialogID').dialog("option", "buttons")["TheButton"].apply()
This worked great for me..
None of these solutions seemed to work for me in IE9. I ended up with this..
$('#my-dialog').dialog({
...
open: function () {
$(this).parent()
.find("button:eq(0)")
.focus()
.keyup(function (e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).trigger("click");
};
});
}
});
Below body is used because dialog DIV added on body,so body now listen the keyboard event. It tested on IE8,9,10, Mojila, Chrome.
open: function() {
$('body').keypress(function (e) {
if (e.keyCode == 13) {
$(this).parent().find(".ui-dialog-buttonpane button:eq(0)").trigger("click");
return false;
}
});
}
Because I don't have enough reputation to post comments.
$(document).delegate('.ui-dialog', 'keyup', function(e) {
var tagName = e.target.tagName.toLowerCase();
tagName = (tagName === 'input' && e.target.type === 'button') ? 'button' : tagName;
if (e.which === $.ui.keyCode.ENTER && tagName !== 'textarea' && tagName !== 'select' && tagName !== 'button') {
$(this).find('.ui-dialog-buttonset button').eq(0).trigger('click');
return false;
} else if (e.which === $.ui.keyCode.ESCAPE) {
$(this).close();
}
});
Modified answer by Basemm #35 too add in Escape to close the dialog.
It works fine Thank You!!!
open: function () {
debugger;
$("#dialogDiv").keypress(function (e) {
if (e.keyCode == 13) {
$(this).parent().find("#btnLoginSubmit").trigger("click");
}
});
},
Give your buttons classes and select them the usual way:
$('#DialogTag').dialog({
closeOnEscape: true,
buttons: [
{
text: 'Cancel',
class: 'myCancelButton',
click: function() {
// Close dialog fct
}
},
{
text: 'Ok',
class: 'myOKButton',
click: function() {
// OK fct
}
}
],
open: function() {
$(document).keyup(function(event) {
if (event.keyCode === 13) {
$('.myOKButton').click();
}
});
}
});

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

What is a Vanilla JS or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
$(document).ready(function() {
$("input[type=text]").focus().select();
});
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
jQuery is not JavaScript which is more easy to use in some cases.
Look at this example:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
Source: CSS Tricks, MDN
This is not just a Chrome/Safari issue, I experienced a quite similar behavior with Firefox 18.0.1. The funny part is that this does not happen on MSIE! The problem here is the first mouseup event that forces to unselect the input content, so just ignore the first occurence.
$(':text').focus(function(){
$(this).one('mouseup', function(event){
event.preventDefault();
}).select();
});
The timeOut approach causes a strange behavior, and blocking every mouseup event you can not remove the selection clicking again on the input element.
HTML :
var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });
Enter Your Text : <input type="text" id="text-filed" value="test with filed text">
Using JQuery :
$("#text-filed").focus(function() { $(this).select(); } );
Using React JS :
In the respective component -
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
my solution is to use a timeout. Seems to work ok
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
This will also work on iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
I know inline code is bad style, but I didn't want to put this into a .js file.
Works without jQuery!
<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>
The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.
If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.
I solved this by removing the mouseup handler as soon as it had been triggered as below:
$("input:number").focus(function () {
var $elem = $(this);
$elem.select().mouseup(function (e) {
e.preventDefault();
$elem.unbind(e.type);
});
});
Hope this helps people in the future...
This will work, Try this -
<input id="textField1" onfocus="this.select()" onmouseup="return false" />
Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.
I know there are already a lot of answers here - but this one is missing so far; a solution which also works with ajax generated content:
$(function (){
$(document).on("focus", "input:text", function() {
$(this).select();
});
});
Like #Travis and #Mari, I wanted to autoselect when the user clicked in, which means preventing the default behaviour of a mouseup event, but not prevent the user from clicking around. The solution I came up with, which works in IE11, Chrome 45, Opera 32 and Firefox 29 (these are the browsers I currently have installed), is based on the sequence of events involved in a mouse click.
When you click on a text input that does not have focus, you get these events (among others):
mousedown: In response to your click. Default handling raises focus if necessary and sets selection start.
focus: As part of the default handling of mousedown.
mouseup: The completion of your click, whose default handling will set the selection end.
When you click on a text input that already has focus, the focus event is skipped. As #Travis and #Mari both astutely noticed, the default handling of mouseup needs to be prevented only if the focus event occurs. However, as there is no "focus didn't happen" event, we need to infer this, which we can do within the mousedown handler.
#Mari's solution requires that jQuery be imported, which I want to avoid. #Travis's solution does this by inspecting document.activeElement. I don't know why exactly his solution doesn't work across browsers, but there is another way to track whether the text input has focus: simply follow its focus and blur events.
Here is the code that works for me:
function MakeTextBoxAutoSelect(input)
{
var blockMouseUp = false;
var inputFocused = false;
input.onfocus =
function ()
{
try
{
input.selectionStart = 0;
input.selectionEnd = input.value.length;
}
catch (error)
{
input.select();
}
inputFocused = true;
};
input.onblur =
function ()
{
inputFocused = false;
};
input.onmousedown =
function ()
{
blockMouseUp = !inputFocused;
};
input.onmouseup =
function ()
{
if (blockMouseUp)
return false;
};
}
I hope this is of help to someone. :-)
I was able to slightly improve Zach's answer by incorporating a few function calls. The problem with that answer is that it disables onMouseUp completely, thereby preventing you from clicking around in the textbox once it has focus.
Here is my code:
<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />
<script type="text/javascript">
var doMouseUp = true;
function TextBoxMouseDown() {
doMouseUp = this == document.activeElement;
return doMouseUp;
}
function TextBoxMouseUp() {
if (doMouseUp)
{ return true; }
else {
doMouseUp = true;
return false;
}
}
</script>
This is a slight improvement over Zach's answer. It works perfectly in IE, doesn't work at all in Chrome, and works with alternating success in FireFox (literally every other time). If someone has an idea of how to make it work reliably in FF or Chrome, please share.
Anyway, I figured I'd share what I could to make this a little nicer.
What is a JavaScript or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
You only need to add the following attribute:
onfocus="this.select()"
For example:
<input type="text" value="sometext" onfocus="this.select()">
(Honestly I have no clue why you would need anything else.)
This worked for me (posting since it is not in answers but in a comment)
$("#textBox").focus().select();
onclick="this.focus();this.select()"
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
Edit: Per #DavidG's request, I can't provide details because I'm not sure why this works, but I believe it has something to do with the focus event propagating up or down or whatever it does and the input element getting the notification it's received focus. Setting the timeout gives the element a moment to realize it's done so.
If you chain the events together I believe it eliminates the need to use .one as suggested elsewhere in this thread.
Example:
$('input.your_element').focus( function () {
$(this).select().mouseup( function (e) {
e.preventDefault();
});
});
Note: If you are programming in ASP.NET, you can run the script using ScriptManager.RegisterStartupScript in C#:
ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );
Or just type the script in the HTML page suggested in the other answers.
I sow this one some where , work perfectly !
$('input').on('focus', function (e) {
$(this)
$(element).one('mouseup', function () {
$(this).select();
return false;
}) .select();
});
I'm kind of late to the party, but this works perfectly in IE11, Chrome, Firefox, without messing up mouseup (and without JQuery).
inputElement.addEventListener("focus", function (e) {
var target = e.currentTarget;
if (target) {
target.select();
target.addEventListener("mouseup", function _tempoMouseUp(event) {
event.preventDefault();
target.removeEventListener("mouseup", _tempoMouseUp);
});
}
});
My solution is next:
var mouseUp;
$(document).ready(function() {
$(inputSelector).focus(function() {
this.select();
})
.mousedown(function () {
if ($(this).is(":focus")) {
mouseUp = true;
}
else {
mouseUp = false;
}
})
.mouseup(function () {
return mouseUp;
});
});
So mouseup will work usually, but will not make unselect after getting focus by input

Categories

Resources