question about input validation after element loses focus - javascript

I started learning javascript, and I am trying to make a little project to play around.
I want to validate that the input field for username contains only letters (uppercase or lowercase) and when the value is correct, to outline the field with a color. (I don't care about the design, i care about functionality since it's purpose is for learning).
I have this code: https://jsfiddle.net/7zcv4g1m/1/
const userField = document.querySelector('#user .user');
const passwordField = document.querySelector('#password .password');
const regEx = /^[a-zA-Z]+$/g;
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = regEx.test(userText);
if (expr == true && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}
userField.addEventListener("focusout", checkUser, false);
My problem is this: at first run, if I click on the element and type a correct text, it outlines the input as expected when I focusOut of the element. The issue is when I click back in the element and just click somewhere outsite of the element to trigger focusout event, without modifying anything in the text. Somehow, my regex condition (the expr variable in the code) is considered to be false, instead of being true, and it turn the element's output back to grey instead of green. If I click back in and after out, it turns back the input border to green.
I don't understand why is this happening and where I made a mistake. Or maybe I wrote the code wrong. If anyone can please give me a hint, will be much appreciated.

It's caused by regEx.test(userText). This should work:
function checkUser() {
// userField.setAttribute('class', 'user');
let userText = userField.value.substring(0, userField.value.length);
let expr = userText.match(regEx);
if (expr && userText.length > 0) {
userField.setAttribute('class', 'user test');
} else {
userField.setAttribute('class', 'user');
}
}

delete modificier g in RegEx, like as
const regEx = /^[a-zA-Z]+$/

Related

how could i know the value of input in textarea HTML only of the word written after spacing?

I'm trying to create something in my website using javascript which'll just alert when the value in textarea typed is suppose "Hello", this should only be applicable for the word after space.
For example:
<textarea id="txtar" cols="30" rows="10"></textarea>
so when I whenever enter Hello then it'll alert
NOTE: typing "hello" and then "hello" again after spacing must also show alert but the problem coming is that it's taking value as hello hello and hence not showing any results.
You're going to want to attach a listener to the text-box:
Like this: Best way to track onchange as-you-type in input type="text"?
If I understand the problem correclty you want to alert when the phrase, in this case, Hello, is added to the input string and is not the same as a previous entry.
const textBox = document.getElementById('txtar');
let lastAlert = ""
const inputHandler = function(e) {
const textValue = e.target.value;
const splitTextValue = e.target.value.split(" ") // split the string by spaces
const lastWord = splitTextValue[splitTextValue.length-1]
if (lastWord === "Hello" && lastAlert !== textValue) {
alert("Alert Something")
lastAlert = textValue;
}
}
textBox.addEventListener('input', inputHandler);
textBox.addEventListener('propertychange', inputHandler); // for IE8
// Firefox/Edge18-/IE9+ don’t fire on <select><optio
This is completely untested, but, in my head, this works.
Using regex you can try this
<textarea id="txtar" ></textarea>
let lastLength = 0;
document.getElementById('txtar').addEventListener('input', (event)=>{
let pattern = /\sHello/ig;
let result = event.target.value.match(pattern);
if(result!=null)
if(result.length>lastLength ){
alert("Hello is typed");
lastLength=result.length;
}
})
Hope it helps

Conditional statements with user input

I'm working on a textbot project, where if I input some text in a textbox, the bot spits out something in the console, fairly simple. However, I've run into a problem that I am very frustrated over, and haven't managed to solve. There's probably a simple solution to this, but I can't find it.
What I want to do, is having the textbox accept a command that consists of the user input + a variable that the user inputs. Something like this:
case "input " + condition {
//do something with condition
}
My question is how do I make the textbox differ between the input and the condition? I hope this question isn't way too hard to understand, but I don't know how else to explain it :P
Edit:
Example:
Textbox input:
"!locate p.actionValue"
Then depending on what actionvalue the person inputs, this should return something like:
if (actionvalue = 32) {
//do something if actionvalue is 32
}
But how do i differ between the command and condition?
You can use a regular expression to match the input and get the condition:
var match;
if (match = input.match(/^!locate (.*)/)) {
var condition = match[1];
// do something with condition
}
You can get more general:
var match = input.match(/^!(\S+)\s+(.*)/);
if (match) {
var command = match[1];
var arg = match[2];
switch (command) {
case 'locate':
...
break;
}
}
You can split your text by "input " and then you will get the command
// array separated by 'input '
var command = textbox.split('input ');
// here you got your command: command[0]
of course you'll need to validate that it actually has 'input ', and what happens in cases like 'input input '

Browser Crashes before Input is Entered

I'm writing a program in javascript that is supposed to be a fast paced typing challenge. The issue is that my script that's checking for input is crashing my browser before I can enter anything. I thought that it'd pause to wait for input but it seems like I might be wrong?
Here is the function that crashes my browser:
var level1 = function () {
var letter;
var ascii;
var ncorrect = 0;
var input = "0";
var timedout = false;
document.getElementById('prompt').text = "Level 1 : Type Here!" // this is supposed to change text on the page... It doesn't work but not that's not my question.
while (ncorrect < 26){
timedout = false;
setTimeout(timedout = true, 5000);
ascii = Math.floor(Math.random() * 122) + 97; // ASCII's of lower case letters
letter = String.fromCharCode(ascii);
document.getElementById('letter').text = letter;
input = document.getElementById('keyinput');
console.log(input);
if(!timedout && input === letter) {
clearTimeout();
ncorrect++;
}
else {
ncorrect = 0;
}
}
return 0;
}
If it's not a simple fix...
What would be a better way of monitoring input and responding to a right answer?
Thanks, I know it's a little broad of a question but I'm struggling to figure out what I'm looking for.
Javascript is already running an event loop in the background, so you don't need your own. This loop runs continuously and checks to see if any events have fired on any of the HTML DOM Elements. For example, if a button has been clicked, the event loop will pick up a click event for that element. You can add event handlers to the element, which are functions that fire when certain events occur to that element. What you want to do is set an event handler for the event that fires whenever the text in your input area (I'm assuming that the user is typing in an input or textarea tag) is fired.
For example, the following simple program will create a typing challenge 100 random characters long
var ncorrect = 0;
var timedout = false;
//select an empty paragraph to fill with text
var challengeText = document.getElementbyId("challengeText");
challengeText.innerHtml = "";
//Append 100 random characters to the paragraph
for (var i=0;i<100;i++) {
challengetText.innerHtml += String.fromCharCode(Math.floor(Math.random() * 122) + 97);
}
//Check the number of characters typed since the last the loop hit the element
var lastCharsTyped = 0;
var charsTyped = 0;
//Grab the user input
var input = document.getElementById("userInput")
//Set the event handler to fire when the user presses a key (technically, when they lift their finger
input.onkeyup = function(keyEvent){
//Ugly ternary to deal with the fact that not all browsers use the same api. If you haven't seen this before it means if which is a key of keyEvent then keyCoe is event.which, otherwise it's event.keyCode
var keyCode = ('which' in keyEvent) ? keyEvent.which : keyEvent.keyCode;
//Check if the key pressed is equal to the character in the text to match at the same position
if (keyCode === challengeText.innerHtml.charCodeAt(input.value.length)) { ncorrect ++} else {ncorrect = 0;}
}
It won't handle deletes or shift very gracefully, but it should give you an idea of the direction to take.
As a stylistic note, its customary to declare and initialize your variables right before you use them, rather than at the start of your program.
You can use setTimeout() and pass in a function that checks the input after whichever time you specify. Here's one way to implement this:
setTimeout( function () {
var textbox = document.getElementById('textbox');
if (textbox.value !== 'The quick brown fox jumps over the lazy dog.') {
alert('You didn\'t pass.');
} else {
alert('Congratulations!');
}
}, 5000);
Type in the phrase "The quick brown fox jumps over the lazy dog."
<input type="textbox" id="textbox"></input>
setTimeout is passed a function expression that checks user input and spits out an alert based on their typing prowess. The second argument 5000 means the function passed into setTimeout will be called at the nearest opportunity after 5000 ms has passed.

How to validate window.prompt in javascript?

Is there a way to validate the text of the input textBox of the prompt box displayed by calling window.prompt() in javascript?
I mean something like to not to close the prompt box when clicking its OK button if the string written in its input textBox contains numbers or other illegal chars defined by me, etc.
No, there is not.
.prompt is native functionality that can't be modified.
If you want input validation, you're going to need to use a custom prompt. It might be worth looking into UI libraries like jQueryUI, for example.
var obj = {};
function validate( str ){
return !! str; //or your own validation
}
function setName ( error_message ) {
var name = prompt( (error_message || '') + "Enter a name: ");
if ( ! validate( name ) ) {
setName( 'Invalid name entered\n' );
} else {
obj.name = name;
}
}
If you really want to use only prompt then this is the solution. But, I'd suggest you to use a modal dialog or create your own component.
You can't validate the input of a prompt before closing it. You could simulate this by creating your own type of prompt, or using jQueryUI.
I came across this exact problem today while writing a bookmarklet which requests user input.
It struck me that it's possible to validate window.prompt simply by using a while loop:
let promptedAnswer = null;
while (promptedAnswer !== 'spoon') {
promptedAnswer = prompt('Complete this phrase: "There is no [ ]."');
}
Working Example:
let chosenNumber = 0;
while ((chosenNumber < 1) || (chosenNumber > 10)) {
chosenNumber = prompt('Choose a number between 1 and 10:');
}
console.log('Your chosen number is ' + chosenNumber);

Find the first character of input in a textbox

I am stuck in implementing the following:
User starts typing in a textbox.
The javascript on page captures the first character typed, validates that it is an english alphabet (a-z,A-Z) and converts it to lowercase (if necessary).
Make an XMLHttp request based on the input (i.e. if first input character is a, get a.xml, if b get b.xml and so on).
I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.
Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.
Something like this should work:
HTML:
<input type="text" id="myField" />
And in JS:
window.onload = function() {
document.getElementById('myField').onkeyup = function() {
// Validate that the first letter is A-Za-z and capture it
var letter = this.value.match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
// Do the request
}
}
}
My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:
$(function() {
$('#myField').keyup(function() {
var letter = $(this).val().match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
$(this).val(letter + $(this).val().substring(1);
// Do the request
}
});
});
What part of the problem do you not know how to do? Here's an approach that you can follow. Very likely to need adjustments, but a good starting point
if our text field's id is 'txt'
document.getElementByID('txt').onkeypress = function(e) {
var textInField = this.value;
if (textInField.length == 1) {
var firstChar = textInField.charAt(0);
if (/[a-zA-Z]/.test(firstChar)) {
sendXHR(textInField.value.toLowerCase())
}
} else {
// What do you do if there is one or more chars???
}
}
Note that the other answers here mention onchange, that doesn't fire until the focus leaves the field, which I don't think is what you want

Categories

Resources