action keyup after the third charecter - javascript

Hi could someone help me figure out how to stop a function running until a specific number of characters are pressed?
currently using the following function:
$('input#q').keyup
this works as soon as you press any key...

Something like this should start firing code after 3 letters have been added:
Live Example
JavaScript
$('input#q').keyup( function() {
if( this.value.length < 4 ) return;
/* code to run below */
$('#output').val(this.value);
});
HTML
<input id="q" />
<br /><br />
<input id="output"/>

you could do :
$('input#q').keyup(function(){
if($(this).val().length > 3)
{
//do something
}
});

You could store the characters in a string variable each time a key is pressed and then run a conditional statement to check the length of the variable. If it's equal to three, run whatever function

Well you'll probably need to take into account the way focus changes. Do you want to clear the counter when the field is newly focused or not? You should also decide whether you're counting characters actually added to the field, or instead if you want to could actual discrete key presses - a "shift" key press, for example, won't add any characters, but it's a key being pressed.
Anyway it'd probably be something like this:
$(function() {
var keyCount = 0;
$('#q').keyup(function() { // "keypress" to count characters
if (++keyCount === 3) {
// do the thing
}
})
.focus(function() {
keyCount = 0; // if this is what you want
});
});
If you're counting the "keypress" event instead of "keyup", you might want to count the actual length of the text field value rather than trying to count events.

How's about:
var c = 0;
('input#q').keyup( function() {
c++;
if (c >= 3) {
startGame();
}
} );

Related

jQuery to prevent user from inputting if regular expression is not matched by using preventdefault

Every time user enter, value is checked with regular expression, I'm trying to restrict user from entering further into input field if regexp is not matched
Using keyup event, preventdefault never fires and using keypress event, user is unable to input at all because in the begining, value in input field shows as "" (nothing)
var discountRegex = /(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/
$("#" + (idOfElement)).on("keyup",function (e) {
var val=this.value
var k = e.keyCode
if(k==46 ||(k > 48 && k <97)){
console.log(k)
return discountRegex.test(val);
}
});
in the above code idOfElement is the id i get on whichever field i focus.
Please refer sample code. If input key is invalid input will not accept it. Also please find fiddle for same in comment.
<input type="text">
$(document).ready(function(){
$("input").bind('keypress', function(e) {
var str = e.keyCode;
if (/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$/.test(str)) {
alert('Invalid')
e.preventDefault();
} else {
alert('Valid');
}
});
});
You can check if the regex is matched and if not you can remove the last char like the example below
I updated the code with keydown example
Example

Make JavaScript Detect Buttons That Are Pressed In a Certain Order

I am trying to make a number keypad from 0 to 9 and when certain numbers get pressed in a certain order an event will happen.
So something like this
if ( button1 gets pressed then button2 then button3 )
alert('You did the code!')
}
else {
alert('You did not do the code')
}
No jQuery please
Thanks!
//sequence is 358
//SOLUTION
sequence = {
check : function(e){
sequence.value += this.textContent;
if (sequence.value == sequence.sequence)
{
alert(1);
sequence.value = "";
}
else
{
if (sequence.timer)
{
clearTimeout(sequence.timer);
}
sequence.timer = setTimeout("sequence.value=''", 1000);
}
},
value : "",
sequence : "358"
}
//THIS CODE ATTACHES CLICK HANDLERS TO THE BUTTON, NOT PART OF THE SOLUTION
Array.prototype.map.call(document.querySelectorAll("button"), function(element){
element.addEventListener("click", sequence.check, false);
});
//end
<button>7</button><button>8</button><button>9</button><br/>
<button>4</button><button>5</button><button>6</button><br/>
<button>1</button><button>2</button><button>3</button><br/>
<button>0</button>
How does this work. I don't want to pollute the global scope with values so I used an object to store the variables and the check method in.
The object is called sequence.
It has three properties
check, the method that checks the input when a button is clicked.
value, that holds the sequence value until the correct sequence is found.
sequence, the property that holds the correct value.
Each button on the page is assigned with a click handler. When clicked it fires sequence.check. Via the this keyword (referring to the button) we extract the number (via textContent). We add that number to the value string. Then we check if the value matches the sequence. If so execute some code (in this case an alert) and reset the value.
There is a timer set. If the user doesn't enter a new number within a second the timer will reset the value. setTimeout does this. The 1000 stands for 1000 milliseconds = 1 second.
I would achieve this by monitoring the keydown event, and if the key is a number, add in to an array. At the same time, check the array contents to see if they are in a certain defined order. If they are, fire whatever you need to do, if not, do nothing but add the key to the array. Once your sequence has been completed, clear the array to make way for a new sequence.
You could get complicated with things like, clearing the array after a certain interval of not completing the sequence etc.
Here is a simple system that does part of what you are looking for:
var buttons = document.querySelectorAll('button'),
i;
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var pressed = document.getElementById('pressed');
pressed.value += this.value + "|";
if (pressed.value === '1|2|3|') {
alert('You unlocked it!');
}
if (pressed.value.length >= 6) {
//Start over
pressed.value = "";
}
}, false);
}
<input id='pressed' type='text' />
<button value='1'>One</button>
<button value='2'>Two</button>
<button value='3'>Three</button>

Javascript capturing keydown

I have a form with many fields and when the user does a "double Enter" in any of the fields doSomething() should happen.
The code below basically works ok, apart from the fact that doSomething() gets called as many times as there are characters in that field. It should only be called once, while if I put "ABC" in the field, doSomething() gets called 3X. It only needs to be called once after 2X Enter, regardless of what was entered in the field.
I (kind of) understand why it's happening (keydown was called 3 times) but have no idea how to fix it. Do I need to unbind something? Resetting the counter to 0 when e.keyCode isn't 13 doesn't seem to make a difference.
EDIT - http://jsfiddle.net/hzr8cezn/ - I'm using 2X SPACE bar character to test since Enter tries to submit the form on jsfiddle. Hit 2X space (in Chrome) and check your console
$("#dynamicFields").on('keydown', 'input', function(e) {
var counter = 0
var field = $(this)
field.keydown(function (e) {
if(e.keyCode == 13) {
counter++;
if(counter == 2) {
console.log('twice!')
doSomething()
}
}
else {
counter = 0
}
})
})
You are attaching to the "keydown" event twice, once using on() and the other using keydown(). You only need to do this once.
Since you are tracking the counter per element, you can use a data() call to track it on the element itself.
// init counter to 0
$("#dynamicFields input").data('counter',0);
// bind to keypress event
$("#dynamicFields").on('keydown', 'input', function(e) {
// the input field
var $field = $(this);
// enter key?
if ( e.keyCode == 13 ){
// how many times?
var counter = $field.data('counter');
// increment it
$field.data('counter',++counter);
// do the stuff
if ( counter >= 2 ){
alert('well, you did it.');
}
} else {
// reset
$field.data('counter',0);
}
})
See it working in this jsFiddle.

Mirroring input content with non-printable chars like CTRL, ALT or shift key

When non-printable char is pressed, it's replaced with let's say for CTRL=17 with "[CTRL]".
Here is code an example
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
the problem is when user presses backspace the second input must reflect the content of the first one, so "[CTRL]" must be deleted at once like any other chars.
You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:
Create a map of all required key codes in an array/object
Handle event for say keydown and listen for keycode
Look for the keycode in your map and if found show it
prevent the default (to prevent e.g. say backspace browsing back)
If not found in map, let the character go thru as usual.
A very basic example:
Demo: http://jsfiddle.net/abhitalks/L7nhZ/
Relevant js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
Edit: (as per the comments)
The concept remains the same, just copying the value to the second input:
Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.
Thanks to #serakfalcon for (that simple solution), which we are using here:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});
You can check in the keydown for the last character in the input field. If it's a ] you can remove everything from the right to the last found opening bracket [. Unfortunatly this does not work if you're cursor is inside '[ ]'.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var element = $(this),
value = element.val(),
lastChar = value.slice(-1);
if(lastChar == ']') {
var lastIndex = value.lastIndexOf('['),
index = value.length - lastIndex;
element.val(value.slice(0, -index) + "]");
}
}
});
Fiddle
you can always use a regex.
$('#textbox1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(CTRL|ALT|SHIFT)\]$/,' '));
}
});
fiddle
Edit: combined with abhitalks code

In jQuery, how to detect specified string while user is typing it?

Much like when typing a comment on Facebook and you hit #username, it reacts to that, letting you choose a username inline.
Using jQuery, how would one go about hooking up an event listener for [text:1]. I want an event to fire when the user has entered [text: into a text field.
Zurb created a textchange plugin that will help. See their "Validate Text" example towards the bottom, i believe its almost exactly what you're looking for..
http://www.zurb.com/playground/jquery-text-change-custom-event
use keyup function to trigger. Split all the string and check it.
[UPDATE]: More Improved Version
<script>
var totalcount=0;
$(function (){
$('#text').keyup(
function (){
var arr = $(this).val().split(" ");
var matchitems = count('hello', arr);
//console.log(matchitems);
if(matchitems > totalcount){
alert('hello');
totalcount = matchitems;
}
if(matchitems < totalcount)
{
totalcount = matchitems;
}
}
)
})
function count(value, array)
{
var j=0;
for(var i=0;i<array.length;i++)
{
if(array[i] == "hello"){
j++;
}
}
return j;
}
</script>
<input type="text" id="text" />
})
</script>
<input type="text" id="text" />
Using keyup like #experimentX mentioned is the way you want to go b/c then you'll know that your user has inputed value then. However, running a for loop would be extremely costly on every single keyup event. Instead, since you know the value you want already, you can use a preset regexp to search for your value:
<input type="text" id="text" value="" />
<script>
$(function () {
var $input = $('#text');
$input.keyup(function (e) {
var regexp = /\[text\:/i,
val = $(this).val();
if (regexp.test(val)) {
console.log('i have it: ', val);
}
});
});
</script>
Here are a couple additional scenarios on how you can write the actual regexp.
You want the string to be at the very beginning of the input: var regexp = /^\[text\:/i;
Building on the one above, but incorporate any amount of whitespace in front of the text you actually want: var regexp = /^\s+?\[text\:/i;

Categories