Limit consecutive characters on keypress with javascript - javascript

i wrote this code for an information booth at a park, it works on html5 and javascript
function myFunction() {
var name = document.getElementById('name').value;
var nameFilter = /^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$/g;
if(nameFilter.test(name)) {
$('#name').keydown(function (e) {
if (e.keyCode == 8 || e.keyCode == 46) {
$(this).unbind(e).keypress();
}
else {
e.preventDefault();
//return false;
}
});
}
};
it is supposed to prevent more than one consecutive characters (the booth keyboard is kinda broken and on key press it puts like 3 to 5 times the pressed key)
so far i've accomplished to limit it to two characters, but then thanks to preventDefault() it does nothing, i used an unbind to restore it but still i've accomplished nothing and i need help with this, whether it be by this mean of any other

This version accounts for capitalizing letters with the shift key
var nameElement = $('#name');
var wasShiftKeyPressed;
var nameAfterFirstKeyDown;
nameElement.keydown(function(e) {
wasShiftKeyPressed = e.shiftKey;
setTimeout(function() {
nameAfterFirstKeyDown = nameAfterFirstKeyDown ? nameAfterFirstKeyDown : nameElement.val();
});
})
nameElement.keyup(function() {
if (wasShiftKeyPressed) {
wasShiftKeyPressed = false;
nameAfterFirstKeyDown = nameElement.val(); //Otherwise capitalization only works for first letter
}
else {
nameElement.val(nameAfterFirstKeyDown);
nameAfterFirstKeyDown = "";
}
});

Related

I want to trigger a function if the characters in a textfield are equal to some number

I want to trigger the following function only if the character count in textfield is equal to 8 else I will do something else. Below is the code I am using, Payment.php has the code for querying data.
$(document).ready(function() {
$('#item').keypress(function (event) {
var key = event.which;
if (key == 13) {
var item = $(this).val().trim();
if(item.length == 8){
var item = $('input#item');
if (item != ''){
$.post('ajax/Payment.php',{user:item}, function(data){
$('div#test').append(""+data+"</br>");
});
};
};
else {
// my code
};
};
});
}):
The problem was solved by removing a line from the code.
var item = $('input#item');
Now I am getting the correct values.

There must be a better way - change search as user input changes

I have a search filter that hides s as the user enters text into a form input. I need it to be dynamic, so that as the user changes their input, the filter refreshes. I accomplished this by having the filter clear on every keyup, but that causes the filter to be delayed and to flash when a word is typed quickly into the filter. You can see what I mean here:
http://cambridgefellows.com/directory-of-fellows/
Here is my jquery:
$(document).ready(function() {
$('input[name=searchFilterInput]').val('');
$('input[name=searchFilterInput]').keyup(function() {
var searchFilterVal = $('input[name=searchFilterInput]').val();
searchFilterVal = searchFilterVal.replace(/ /g, '-');
searchFilterVal = searchFilterVal.toLowerCase();
$('tr.hide').fadeIn('slow').removeClass('hide');
if(searchFilterVal == '') {
$('tr.hide').fadeIn('slow').removeClass('hide');
} else {
$('tr.fellows').each(function() {
var pattern = $(this).attr('class'); // the pattern to be matched
var match = pattern.match(searchFilterVal);//If pattern matches it returns the match
if(!match) {
$(this).fadeOut('normal').addClass('hide');
} else {
}
});
}
});
$('#searchForm').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
});
I think there must be an easier way to handle this so that the filter dynamically updates as the user enter or alters their search text. Can someone more experienced than me look at this an enlighten me to the obvious thing that I'm overlooking? Thank you so much for your help.
Looks like you need a setTimeout and clearTimeout.
var timer;
$('input[name=searchFilterInput]').keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var searchFilterVal = $('input[name=searchFilterInput]').val();
searchFilterVal = searchFilterVal.replace(/ /g, '-');
searchFilterVal = searchFilterVal.toLowerCase();
$('tr.hide').fadeIn('slow').removeClass('hide');
if(searchFilterVal == '') {
$('tr.hide').fadeIn('slow').removeClass('hide');
} else {
$('tr.fellows').each(function() {
var pattern = $(this).attr('class'); // the pattern to be matched
var match = pattern.match(searchFilterVal);//If pattern matches it returns the match
if(!match) {
$(this).fadeOut('normal').addClass('hide');
} else {
}
});
}
}, 300);
});
That way whenever a user hits the next key, the timeout will be cleared from the previous keypress and the code will only execute for the current keypress.
Reduce the milliseconds if you feel it's not updating fast enough.

How to get my loop to start from the beginning after error detected

I am trying to get my loop to restart when it comes across an user input error. I need it to restart at the very beginning and not just the last question.
So below when it says validImput = false this is where I am trying to get it to restart.
{
var validInput = true;
var start = confirm('Add item to shoping cart');
if (start == true) {
// ask first question
var orderProductCodeArr = parseInt(prompt('Enter input: '), 10);
if (isNaN(orderProductCodeArr)) {
alert("input is not a valid number");
validImput = false
} else if (orderProductCodeArr < 0 || orderProductCodeArr >= PRODUCT_LIST.length) {
alert("code does not match any item");
validInput = false;
}
// ask second question
else if(validInput == true) {
var item = PRODUCT_LIST[orderProductCodeArr];
alert("item is: " + item);
}
// get quantity input
var quanityArr = parseInt (prompt('Enter quality amount'),10);
if (isNaN(quanityArr)) {
alert("input is not a valid number");
validInput = false;
}
} else {
document.writeln('still to come')
}
}
The usual method of starting something over is some sort of loop construct, often using while like this:
while (true) {
// your loop code here
// you can use break; to break out of the while loop
// anywhere to stop repeating
// you can use continue; to jump to the next iteration immediately
}
Or, sometimes you use a loop condition like this:
var doAgain = true;
while (doAgain) {
// within the loop, you set doAgain to false when you are done
// and don't want to repeat the loop again
}
try
function test()
{
for(var s=0;s<5;s++)
{
try
{
//body of the for loop
}catch(e){s=0;}
}
}

catch key and trigger function using jQuery or plain js

I have a textarea inside a form:
<textearea id="message"></textarea>
While typing, whenever a user types the character # inside the textarea, I want to trigger a function for every character typed afterwards and till the user hits enter or space bar.
How is this possible using jQuery or plain JS ?
You can use this :
var myCallback = function () {
//put your code here
}
(function (callback) {
var jMessage = $('#message'),
callbackCallable = false,
keycodeEnter = 13,
keycodeSpace = 32;
jMessage.keyup(function (e) {
var lastLetter = jMessage.val().slice(-1);
if (lastLetter === '#') {
callbackCallable = true;
} else if (e.keyCode === keycodeEnter || e.keyCode === keycodeSpace) {
callbackCallable = false;
} else if (callbackCallable) {
callback();
}
});
}(myCallback));
If you want to detect only typing you can listen for a key pressed event.
var anyHitYet = false;
jQuery('#massage').keydown(function (event) {
if (anyHitYet) return;
var key = event.keyCode;
if (key === 51) {
//call your function here
} else if (key === 13 || key === 32) {
anyHitYet = true;
}
});
Basically if it's 51 then # is hit so call your function if space or enter are hit your #-when-pressed-function won't be executed until you make anyHitYet=false again
Somebody might paste something though so then it is a different story
Not sure if the above answers do what the OP wants.
I think a second or third # should be monitored aswell, till a space or return ends monitoring.
// have a flag somewhere and initialize it to FALSE
var doMonitor = FALSE;
$('#message').keydown(function(event){
// trigger monitoring after # was tipped
// (only once till space or return reset)
if(event.keyCode == 51 && !doMonitor){
doMonitor = TRUE;
}
else if(event.keyCode == 32 || event.keyCode == 13)
doMonitor = FALSE;
else if(doMonitor){
// do whatever needs to be done
}
});
You may also add an attribute to your #message textarea and remove it (or change its value) instead of using a variable.
// for setting an attribute
.attr( attributeName, value )
// for removing it
.removeattr( attributeName )
look here http://api.jquery.com/removeAttr/ and here http://api.jquery.com/attr/

progressive konami code

I am trying to create a .js file for a website that upon entering the konami code Up, Up, Down, Down, Left, Right, Left, Right, B, A, Start(enter) it will embed a video.
However while entering the right keys the webpage should display something like "keep going", if a wrong key is entered it should display "wrong, try again", and allow them to start over.
I've manged to get the JavaScript working where upon entering the right code it displays an alert, and entering the wrong code displays a different code.
i've manged to get this much code using online resources but none of them explain how to get wrong, try again part
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
if (keys.toString().indexOf(konami) >= 0)
{
alert('Right');
keys = [];
};
if (keys.toString().indexOf(konami) < 0)
{
alert('Wrong');
keys = [];
}
}, true);
};
Any help would be greatly appreciated.
if (window.addEventListener) {
var index = 0;
var konami = [38,38,40,40,37,39,37,39,66,65,13];
window.addEventListener("keydown", function(e){
if (e.keyCode === konami[index])
{
index++; //valid key at the valid point
if (index == konami.length)
{
alert("Correct");
} else {
alert("Keep going");
}
} else {
// incorrect code restart
index = 0;
alert("Wrong");
}
});
}
You could do something like
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13".split(',');
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
console.log(e.keyCode);
var lengthOfKeys = keys.length -1;
if (konami[lengthOfKeys] == keys[lengthOfKeys])
{
alert('Right');
if(konami.length === keys.length){
alert('complete!');
}
}else{
alert('Wrong');
keys = [];
}
}, true);
};
fiddle here http://jsfiddle.net/b6kuZ/
This works for me:
if (window.addEventListener) {
var keys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
konami_arr = konami.split(',');
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
var position = keys.length-1;
if(keys[position ] != konami_arr[position])
{
alert('Wrong');
keys = [];
}
else if (keys.join(',') == konami)
{
alert('Right');
keys = [];
};
}, true);
}
​jsFiddle exmaple
Having an alert come up every time a key is hit is very jarring. Instead, why mot have the validation of correct answers show up in a DIV, and only use an alert when the answer is incorrect.
function checker(){
if (kc==11){
kc=0; // This resets the sequence.
// The function for what you want to occur goes here.
}
}
function keyUp(e) {
var keynum;
if (window.event){keynum = event.keyCode;}
else if (e.which){keynum = e.which;}
for (i=0;i<222;i++){
// The 222 represents all the keys on the keyboard.
var kx=konamicode[kc]; // kx represents the current position in the code sequence.
var res=document.getElementById('response');
var dumb=wrong[kc];
if (keynum==i){
// Checks to see if key matches sequence, and resets sequence if it doesn't.
if (i!=kx){
res.innerHTML='';
alert(dumb); // Reprimands user, and resets the sequence.
kc=0;
}
else {
res.innerHTML=right[kc]; // Congratulates user, and advances the sequence.
kc++;
}
}
}
checker();
}
document.onkeyup = keyUp;
In the body of the page you will need to put a DIV to display that key strokes were validated as correct.
<div id="response"></div>

Categories

Resources