I'm struggling with the following problem. I have input text element. I want a user to enter something there and then his value appears as a normal text (the input should disappear).
I searched for a few solutions but nothing worked for me. What I tried (whatever function I provide, I get no results, what should I provide to get the effect I described above and how to make it happen?):
$('input.modified').on('input', function(){
(this).append('<p>some</p>');
});
OR
$("input.modified").bind("propertychange change keyup paste input", function(){
$(this).append("<p>dgdgd</p>");
});
OR
$("input.modified").change(function(){
$(this).css("visibility","hidden");
}); //end change function
How to make functions like .on() or .change() work with my code?
thanks for all the answer, but I can't move your examples to my code :(
Please verify this fiddle what I'm missing:
[http://jsfiddle.net/w6242/][1]
Check this DEMO
HTML:
<input class="modified" type="text"/>
<p></p>
JS:
$("input.modified").change(function(){
$('p').html($(this).val());
$(this).css("visibility","hidden");
});
check this
Fiddle
$("#in").focusout(function(e){
$("span").html(($("#in").val()));
$(this).hide();
});
Here a fiddle http://jsfiddle.net/keypaul/NsWC5/5/
HTML
<div id="wrapper">
<input type="text" id="writer" />
send
</div>
JQuery
$("#submit").click(function(e){
var txt = $("#writer").val();
$("#writer").fadeOut(400);
$("#submit").fadeOut(400, function(){
$("#wrapper").append('<div id="text">' + txt + '</div>').hide().fadeIn(600);
});
e.preventDefault();
});
If you need to do that with onther event (instead of a click submit) you can use onchange or focusout applied to your input element
At its simplest, assuming you really want to replace the input:
$('#demo').on('keyup', function(e){
if (e.which === 13) {
var p = $('<p />', {
text : this.value
});
$(this).replaceWith(p);
}
});
JS Fiddle demo.
Or, to insert an adjacent element and simply hide the input:
$('#demo').on('keyup', function(e){
if (e.which === 13) {
var span = $('<span />', {
text : this.value
});
$(this).hide().after(span);
}
});
JS Fiddle demo.
The above jQuery works with the following demonstrative HTML:
<input id="demo" type="text" />
References:
after().
hide().
on().
replaceWith().
Hereis the code and online JsFiddle:
<div class="blocka"></div>
<div class="blockb"></div>
$(".blocka").mouseenter(function(){
$(".blockb").show();
});
$(".blocka").mouseleave(function(){
$(".blockb").hide();
});
My question is is it possible to have something like
if $(".blocka") or $(".blockb") mouseleave then hide $(".blockb")
I tried the following but it doesn't work :
$(".blocka" || ".blockb" ).mouseleave(function(){
$(".blockb").hide();
});
You can do multiple selections using a comma ,:
$(".blocka, .blockb").mouseenter(function(){
$(".blockb").show();
});
$(".blocka, .blockb").mouseleave(function(){
$(".blockb").hide();
});
Updated fiddle:
http://jsfiddle.net/jaUNY/3/
$(".blocka, .blockb" ).mouseleave(function(){
$(".blockb").hide();
});
multiple selectors will work.
http://api.jquery.com/multiple-selector/
You may want to keep blockb open when moving mouse from blocka to blockb, so the code would be:
$(".blocka, .blockb").hover(
function() { $(".blockb").show() },
function() { $(".blockb").hide() }
);
I have this HTML:
<div class="container">
select this
select this
select this
</div>
click here to begin selecting
And I have this JS/jQuery snippet of code:
$('a[href="#begin"]').blur(function(e) {
console.log( e.target.href ); // this will output: #begin
});
So what I need with .blur is to determine which element got focus after the <a href="#begin"> was blured.
Is this possible with JS/jQuery?
It's not possible to know which element got the focus from the blur event itself. You would need to add a click event to get that, like this:
$('a[href="#begin"]')
.blur(function(e) {
console.log( e.target.href ); // previous link href
});
.click(function(e) {
console.log( e.target.href ); // current link href
});
An other possible way could be:
SEE DEMO
$('a[href="#begin"]').blur(function(e) {
setTimeout(function(){console.log( $(document.activeElement).attr('href') );},0);
});
You can check which element gets focus by using the .focus method, similar to .blur
During your blur event, you can set a flag to "look out" for the next control focus. In your focus function, if this flag is set then you know your "being" field was the last one to lose focus. You will also need to reset the flag when any other field is blurred though.
Here is a simple concept example...
var beginWasLast = false;
$('a[href="#begin"]').blur(function(e) {
e.preventDefault();
beginWasLast = true;
console.log( e.target.href ); // this will output: #begin
});
$('a[href="#begin"]').click(function(e) {
e.preventDefault();
});
$('a:not(a[href="#begin"])').blur(function(e) {
e.preventDefault();
beginWasLast = false;
});
$('a:not(a[href="#begin"])').click(function(e) {
e.preventDefault();
if(beginWasLast){
console.log( e.target.href );
}
});
Here is a working example
I added in the e.preventDefault(); calls so that the page didn't reload when the links were clicked.
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.
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