This is a followup question to this question:
select all contents of textbox when it receives focus (Javascript or jQuery)
Basically I am using a textbox in conjunction with the jQuery masked input plugin(Edit: Link may no longer point at relevant version)
When the masked input textbox receives focus I want to select all of the contents of that textbox, but it seems as though having this plugin binded to the textbox prevents that. I was just wondering if there was a way around this.
Below is a sample .html page that demonstrates the issue:
<html>
<head>
<title></title>
</head>
<body>
<input id="masktest" type="text" value="01/01/2009" />
<br />
<input id="focustest" type="text" value="on focus will select all contents..." />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.1.pack.js"></script>
<script type="text/javascript">
$(function() {
$("#masktest").mask("99/99/9999");
// Contents of textboxes will be selected when receiving focus.
$("input[type=text]")
.focus(function() {
$(this).select();
});
});
</script>
</body>
</html>
I'm the author of the Masked Input Plugin for jQuery. I decided that this should be the default behavior for completed masks and I got it into the latest release. You can read the details here
Hey Jon, not too sure about the performance of this, but this should work:
$(function() {
// Contents of textboxes will be selected when receiving focus.
$("input[type=text]")
.focus(function() {
var mask = "99/99/9999";
$(this).unmask(mask).select().mask(mask);
});
});
its working for me in FF3.
$("input[type=text]").focus(function(e) {
var that = this;
setTimeout(function(){$(that).select();},10);
return false;
});
setTimeout will "queue" the select() execution, I was wondering about:
- Ok mask functions do your work THEN I'll select the content. That THEN is where the queue is useful.
Just an idea. I hope it works as expected.
Problem
Defaut value is deleting when focus
Resolve : added little patch code to mask.js file (jquery.maskedinput-1.2.2.min.js)
(function(a){var c=(a.browser.msie?"paste":"input")+".mask";var b=(window.orientation!=undefined);a.mask={definitions:{"9":"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"}};a.fn.extend({caret:function(e,f){if(this.length==0){return}if(typeof e=="number"){f=(typeof f=="number")?f:e;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(e,f)}else{if(this.createTextRange){var g=this.createTextRange();g.collapse(true);g.moveEnd("character",f);g.moveStart("character",e);g.select()}}})}else{if(this[0].setSelectionRange){e=this[0].selectionStart;f=this[0].selectionEnd}else{if(document.selection&&document.selection.createRange){var d=document.selection.createRange();e=0-d.duplicate().moveStart("character",-100000);f=e+d.text.length}}return{begin:e,end:f}}},unmask:function(){return this.trigger("unmask")},mask:function(j,d){if(!j&&this.length>0){var f=a(this[0]);var g=f.data("tests");return a.map(f.data("buffer"),function(l,m){return g[m]?l:null}).join("")}d=a.extend({placeholder:"_",completed:null},d);var k=a.mask.definitions;var g=[];var e=j.length;var i=null;var h=j.length;a.each(j.split(""),function(m,l){if(l=="?"){h--;e=m}else{if(k[l]){g.push(new RegExp(k[l]));if(i==null){i=g.length-1}}else{g.push(null)}}});return this.each(function(){var ORJ=$(this).val();var r=a(this);var m=a.map(j.split(""),function(x,y){if(x!="?"){return k[x]?d.placeholder:x}});var n=false;var q=r.val();r.data("buffer",m).data("tests",g);function v(x){while(++x<=h&&!g[x]){}return x}function t(x){while(!g[x]&&--x>=0){}for(var y=x;y<h;y++){if(g[y]){m[y]=d.placeholder;var z=v(y);if(z<h&&g[y].test(m[z])){m[y]=m[z]}else{break}}}s();r.caret(Math.max(i,x))}function u(y){for(var A=y,z=d.placeholder;A<h;A++){if(g[A]){var B=v(A);var x=m[A];m[A]=z;if(B<h&&g[B].test(x)){z=x}else{break}}}}function l(y){var x=a(this).caret();var z=y.keyCode;n=(z<16||(z>16&&z<32)||(z>32&&z<41));if((x.begin-x.end)!=0&&(!n||z==8||z==46)){w(x.begin,x.end)}if(z==8||z==46||(b&&z==127)){t(x.begin+(z==46?0:-1));return false}else{if(z==27){r.val(q);r.caret(0,p());return false}}}function o(B){if(n){n=false;return(B.keyCode==8)?false:null}B=B||window.event;var C=B.charCode||B.keyCode||B.which;var z=a(this).caret();if(B.ctrlKey||B.altKey||B.metaKey){return true}else{if((C>=32&&C<=125)||C>186){var x=v(z.begin-1);if(x<h){var A=String.fromCharCode(C);if(g[x].test(A)){u(x);m[x]=A;s();var y=v(x);a(this).caret(y);if(d.completed&&y==h){d.completed.call(r)}}}}}return false}function w(x,y){for(var z=x;z<y&&z<h;z++){if(g[z]){m[z]=d.placeholder}}}function s(){return r.val(m.join("")).val()}function p(y){var z=r.val();var C=-1;for(var B=0,x=0;B<h;B++){if(g[B]){m[B]=d.placeholder;while(x++<z.length){var A=z.charAt(x-1);if(g[B].test(A)){m[B]=A;C=B;break}}if(x>z.length){break}}else{if(m[B]==z[x]&&B!=e){x++;C=B}}}if(!y&&C+1<e){r.val(ORJ);w(ORJ.length,h)}else{if(y||C+1>=e){s();if(!y){r.val(r.val().substring(0,C+1))}}}return(e?B:i)}if(!r.attr("readonly")){r.one("unmask",function(){r.unbind(".mask").removeData("buffer").removeData("tests")}).bind("focus.mask",function(){q=r.val();var x=p();s();setTimeout(function(){if(x==j.length){r.caret(0,x)}else{r.caret(x)}},0)}).bind("blur.mask",function(){p();if(r.val()!=q){r.change()}}).bind("keydown.mask",l).bind("keypress.mask",o).bind(c,function(){setTimeout(function(){r.caret(p(true))},0)})}p()})}})})(jQuery);
if your 'completed' function doesn't work, try to replace this line:
if (settings.completed && next == len)
(this is line number 169 of noncompressed plugin) with that:
if (settings.completed && eval(+next - 1) == len)
While using this plugin with firebug, i've noticed, that 'next' variable jumps up over a symbol when last char of mask entered.
This way should work.
I found a better solution than timeout.
You can view jquery.maskedinput.js:293 there is a function for input focus and it is triggered only on inputs without "readonly" attribute so:
$("input[type=text]").attr("readonly", true).select().removeAttr("readonly");
...just like that. Works like a charm ;)
Related
I am trying to validate the input field value. If it's the wrong to value, the focus should be retained in the same input field when I used either on blur and onfocusout. Please help me out.
Here is my code:
$(document).ready(function(){
$("#txt_fname").on("focusout", (function(evnt){
if ($(this).val() != "name"){
event.preventDefault();
//$("#txt_fname").focus().trigger('focusin');
$("#txt_fname").focus();
return false;
}
})
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<input type="text" id="txt_fname" name="txt_fname" value="" placeholder="Enter a First name" maxlength="10">
<input type="text" id="txt_lname" name="txt_lname" value="" placeholder="Enter a Last name" maxlength="10">
The snippet is working fine, but in my localhost using xampp, it's not working. Even, I changed the Jquery version too:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
I don't know, what is the issue behind this. Please help me.
Thanks!
Hope this code will help:
$(document).on("focusout", "#txt_fname", function()
{
if ($(this).val() != "name")
{
$("#txt_fname").focus();
return false;
}
})
Found a typo in your code which probably caused the issue, in the word evnt:
$(document).ready(function(){
$("#txt_fname").on("focusout", (function(evnet){ //you typed "evnt" by mistake
if ($(this).val() != "name"){
event.preventDefault();
//$("#txt_fname").focus().trigger('focusin');
$("#txt_fname").focus();
return false;
}
})
);
});
Tested in my localhost, works like a charm.
Update
Since the OP said that he is using Firefox, while I tested it in Chrome, I realized that maybe it is a browser related issue.
After a bit of digging, I realized that if you focus out from an element and right after that you try to focus in again by using a script, for some reason (maybe a bug?) Firefox doesn't have enough time to blur and focus again.
By using JavaScript setTimeout and setting the time to a pretty low value (I used 10 milliseconds in the example) and putting the focus function inside of the timeout callback, I managed to solve the issue.
setTimeout(function() {
$("#txt_fname").focus();
}, 10);
Hi I want to simulate a user clicking on an input box.
script is:
function prepareToScan(){
$("fireRegAdd").focus();
$('fireRegAdd').keypress();
}
and HTML is
<h2>Add a visitor to today's fire register</h2>
<input type="button" onmousedown="prepareToScan()" value="Add Visitor">
<input id="fireRegAdd" name="fireRegAdd">
</div>
I have a barcode scanner which puts the code into the input box but only when it's been "clicked". I've tried .focus() but it needs two scans to get the scan to work. The on focus is not the same as actually clicking in the box. Does any one know how to do that?
thanks
So I've found that if I add in an alert it set it correctly :
function prepareToScan(){
alert("ready to scan");
$("fireRegAdd").focus();
$('fireRegAdd').keypress();
}
but I don't really want an alert box
I've added a demo of the code. When you click on the button I want there to be a blinking cursor in the input box.
function prepareToScan(){
$("#fireRegAdd").focus();
$('#fireRegAdd').click();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<h2>Add a visitor to today's fire register</h2>
<input type="button" value ="Add Visitor" onmousedown="prepareToScan()"/>
<input id="fireRegAdd" name="fireRegAdd" value="" />
</div>
I've discovered that it's virtually impossible to focus on an input box so that the curso blinks. I tried everything including manipulating the cursor position and using a click event.
I did however solve my problem. Barcode scanners act like keyboards. So I wrote some code which detects keyboard input. It checks for incoming keys. If it receives more than 3 in 250 ms it assumes that it is coming from the scanner. Works a treat. It'd be easy to modify to adjust for different applications. Here's the javascript code I ended up with. To make it work you need a div with id="barcode" Hope someone finds it useful.
var chars = [];
var pressed = false;
window.addEvent( 'keydown', function( evt ){
//console.log(evt.key);
chars.push(evt.key);
setTimeout(function(){
if (chars.length >= 3) {
var barcode = chars.join("");
$("barcode").value= barcode;
}
chars = [];
pressed = false;
},250);
});
Given a keydown event in the browser, how can I predict whether that key event will result in character input? For example, hitting the left arrow doesn't input characters but hitting the a key inputs an A (unless ctrl or alt is down).
I don't need to know what character will be input, just whether the key event will result in an input.
I'm targeting Chrome. Bonus points if your solution works in an IME.
Note: I'm asking about the keydown event, not a downstream event like keypress or oninput.
There's an HTML 5 event: input. MDN: https://developer.mozilla.org/en-US/docs/Web/Reference/Events/input. Other than that there's no proper solution.
Ok, I think I have a solution. I don't know how good it is but it works. Have a look: http://jsfiddle.net/tLPsL/
It's basically saving the value of the input onkeydown and checking it in onkeyup.
$('#sattar').keydown(function() {
window.SATTAR = $(this).val();
});
$('#sattar').keyup(function() {
if(window.SATTAR !== $(this).val()) {
alert("changed");
}
});
[updated]
use this
$(document).keydown(function(event){
console.log(event.which);
});
and filter the value of the event.which according to your needs using the ascii values and exclude the numbers that appear with unwanted buttons
for example (this example demonstrates accepting small letters only):
$(document).keydown(function(event){
var x = event.which;
if (x <= 90 && x >=65) console.log('accepted');
else console.log('not accepted');
});
JSFiddle
[update] :
If you don't like this method you can use another that detects an input to any textfield or textarea :
$('input,textarea').change(function(){
console.log('input detected!');
});
$(document).keyup(function(event){
var x = $(event.target);
if (x[0].nodeName == 'INPUT' || x[0].nodeName == 'TEXTAREA'){ //you can filter the backspace if you don't want to consider it a change on the input by anding it with the whole argument here using the key number explained above
x.blur().focus();
}
});
DEMO
note: The first method works for all languages as the same keyboard keys are used for inputs of different characters but they still can type.
Sources && tips:
I saw the characters keydata list in this site.
-To make it crossplatform and crossbrowser, I suggest you to watch this site
-You can test the keydown event here.
-Jquery also suggest to use key which because it normalizes keycode and charcode (i think this can be usefull for the crossbrowser part but I didn't find a table like the one I posted before for keycode), see details here.
To the end, a personal thought: I wouldn't appear rude by telling this so please, try to understand, you had 3 clear and working answer, should be your interest to improve details to make it working as you need, especially because, for many reason, (like time, hardware disponibility, no one pay us, freelancer site is elsewhere, etc etc), who are helping you, maybe, can't do your entirely work.
EDIT
Considering your needs, I wrote this code, keeps in mind that combination key are hard to handle, so, you should test this example before to re-use it. fiddle
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).keydown(
function(event){
if(event.target!='[object HTMLBodyElement]'){//Are we in an input?
if(!event.ctrlKey && !event.altKey){//Are we using a combo ctrl or alt?
if(event.keyCode==13 || event.keyCode==8 || event.keyCode==32 || (event.keyCode>45 && event.keyCode<91) || event.keyCode==188 || (event.keyCode>189 && event.keyCode<193) || (event.keyCode>218 && event.keyCode<222)){
//It is a char?
document.getElementById('valid').innerHTML+=event.keyCode+' ';
document.getElementById('idlast').innerHTML=event.target.id;
}
}
}
}
);
</script>
</head>
<body>
<input id="a" type="text"></input>
<textarea id="b">a</textarea>
<div id="c" contenteditable="true">a</div>
<div id="d" style="width:200px;height:200px;background-color:red">a</div>
last keydown in: <span id="idlast"></span><br>
for keypress in input:<span id="valid"></span><br>
</body>
</html>
END EDIT
For first if the focus is on an object that is not an input(textarea,contenteditable...) you are targeting the body. So if the target is the body, for sure you are not writing somewhere.
Then I suggest you to see this example, keypress is probably usefull for your aim, because it seems to don't register keys that aren't an input.
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).keypress(
function(event){
if(event.target!='[object HTMLBodyElement]'){
document.getElementById('valid').innerHTML=document.getElementById('valid').innerHTML+event.keyCode+' ';
document.getElementById('idlast').innerHTML=event.target.id;
}else{
document.getElementById('out').innerHTML=document.getElementById('out').innerHTML+event.keyCode+' ';
}
}
);
$(document).keydown(function(e){document.getElementById('down').innerHTML=document.getElementById('down').innerHTML+e.keyCode+' ';});
</script>
</head>
<body>
<input id="a" type="text"></input>
<textarea id="b">a</textarea>
<div id="c" contenteditable="true">a</div>
<div id="d" style="width:200px;height:200px;background-color:red">a</div>
last keypress input id: <span id="idlast"></span><br>
for keypress in input:<span id="valid"></span><br>
for keypress out:<span id="out"></span><br>
for keydown:<span id="down"></span><br>
</body>
</html>
I am trying out this simple code which is supposed to shift the focus to another text box when a right click is detected on the first, so that any subsequent paste event makes the text to be pasted into the 2nd box:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#real").bind("contextmenu",function() {
$("#paste").focus();
});
});
</script>
</head>
<body>
<input type = 'text' sh = '0' right = '0' id = 'real' />
<input type = 'text' id = 'paste' />
<p>Dummy</p>
</html>
In Opera above versions 12, it is working fine. However, in 11 and below, even though the focus does get shifted to the 2nd text box on right clicking on the first, the paste event pastes the text in the first textbox (with the focus being shifted to the 2nd textbox immediately, on its own). I tried to replace the code by setTimeout(function() { $("#paste").focus(); },0);, still the error persists.
Can anyone tell me how do I fix this, so that the text gets pasted in the 2nd textbox? (Detecting a mouseup, checking whether it's a right click through event.which, if so, shift the focus - yeah, I did that too, same result!)
As an alternative solution...
$("#real").bind("contextmenu",function() {
$("#paste").val($(this).val());
$(this).val('');
});
I want to display a few images (probably 5 max) and have a user click to select one. First thing I tried was radio buttons and putting the images inside labels.
<input type="radio" name="BackgroundId" id="BackgroundId" value="1" />
<label for="BackgroundId"><img src="../../Content/images/thumb_1.jpg" /></label>
Firefox will select the radio button when the user clicks the image, but IE doesn't.
Is there a jquery plugin that will make the images clickable? Fancy-form looks like something I could use, but it isn't jquery and I've already got jquery in my project.
Or can someone point me to a better way of selecting a single image?
Something like
$(function(){
$("label img").click(function(){
var parent = $(this).parent();
$("#" + parent.attr("for")).attr("checked", "checked");
});
});
Just drop this javascript into your page. I have tested it.
<script language="javascript" type="text/javascript">
$(document).ready(
function ()
{
var selImg = $("#BackgroundId").next("label").find("img");
selImg.click(
function ()
{
$("#BackgroundId")[0].click();
});
});
</script>
The code reads:
Get all the next element after those elements that have an id='BackgroundId'
Now find an img element inside each one.
Set the click events if each found img to call a function that will simulate a click on all those elements that have an id='BackgroundId'.
Please note that even though I am writing "all those" and "each tag", since there is only one tag with the id of 'BackgroundId', all these things are happening singularly.