Javascript - Detecting the first character and alerting the user - javascript

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.

If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}

Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.

charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

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

Comparing string values and showing correct 'answers' in javascript

I am fairly new to Javascript and am trying to learn to write a program that shows a text in one language (eg. Spanish) and has an input box, where the user will type the translated (eg. English) word. The user input would then be compared to the translated word to see if they are the same. I also want to allow some tolerance in case the user inputs a word without an accent if there is supposed to be one (eg. esta instead of está) it won't be counted wrong. If they are not the same I want to be able to show the correct word compared to what the user put. I've been trying to work on this for quite some time but have been getting stuck frequently (for instance, when I run the other function to check the values it opens a new instance when I want it all to be displayed on the same page). Any help with this would be greatly appreciated. Here's what I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Flashcards</title>
</head>
<body>
<script>
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
</script>
<p>English Translation: <input id="english_word" type="text" name="LastName" value="" ></p>
<input type="button" id="myBtn" onclick="check()" value="Check">
<input type="button" id="button" onclick="differentword()" value="Different Word">
<script>
function check()
{
var english_word= document.getElementById('english_word').value;
if (english_word == English) {
document.write("Correct");
}
else {
document.write("Wrong: ");
document.write(Spanish+" in English is "+English);
}
}
function differentword() {
var number = Math.floor((Math.random()*2));
var spanish_word = ["hola","adios"]
var Spanish = spanish_word[number];
var english_word = ["hi","bye"];
var English = english_word[number];
document.write("Spanish: " + Spanish);
}
</script>
</body>
</html>
Or, if you want to see how it runs, you can check it out here https://code.sololearn.com/WXHZ5aAcE3dg/#html.
You got 2 problems here.
You haven't set the current <input id="english_word" type="text" name="LastName" value=""> any value at all (by both html/js). You should set it to the current word (as a string) to manipulate it later.
the if statement if (english_word == English) is broken because it checks if english word, which is a string, equals to an array. and its not, and will never be.
However, checking if the current string word equals to a string, is not a good way in my option. I would like better to use an index to current word that is showing and manipulating that index.
What I suggest is you fix the above by using a new variable: current_word_index, so you can use it in program to check the answer by knowing the current word that is showing.
This next code is just an example of how to currently retrieve by index from arrays:
var current_word_index = 0; // this 0 will change to rand()
var english_word = ["hi","bye"];
english_word[current_word_index];
// english_word will be string "hi".
Here's my full answer:
https://fiddle.jshell.net/j44fjh35/15/
Summary of your question
My understanding is your trying to test the users knowledge on a secondary language ie: Spanish, French etc.
Solution
Switch or If statements are ways to test and compare variables against one another
what you will need to do is first of all convert the string variable to lowercase to ensure that what ever the user types in is always the same.
You will also need to fix some of your code.
So lets look at that first...
var number = parseInt((Math.random()*1));
var spanish_word = ["hola","adios"];
spanish_word is an array which starts from 0 not 1.
Your randomly generated number stored as "number", will equally need to be 0 or 1, simple integer will be sufficient.
Unless your submitting this to a server to be handled by some backend code in PHP or ASP etc, you dont need the "name" attribute here
name="LastName"
You are then over-riding the array
At the start you are setting the array with the following values
var english_word = ["hi","bye"];
But when you click the button to check if you have the right answer
You are erasing the above and telling it to be what ever the user typed in
var english_word= document.getElementById('english_word').value;
There is no need to keep setting and un-setting the array
Try to use better naming convensions for your variables
abbreviate them with what data types they are:
arrEnglishWord to symbolise its an array
strEnglishWord to symbolise it is a string
intEnglishISOCode to symbolise a numerical integer
blEnlish to symbolise a boolean
A lot of code repetition:
Using the an event listener you can save the code repetition
document.addEventListener("DOMContentLoaded", differentword, false);
will make the function differentword run when the page loads, allowing you to get rid of the repeated code at the top
Solution
We need to make the comparison fair (ie not case sentisive)
var strAnswerGiven = english_word.toLowerCase();
var strCorrectAnswer = English.toLowerCase();
if (strAnswerGiven == strCorrectAnswer) {
var arrSpanishWords = ["Hola", "Adios", "Purta", "Luz"];
var arrEnglishWords = ["Hello", "Goodbye", "Door", "Light"];
var strWord = undefined;
var divAnswer = undefined;
function funCheck(elName){
var stAnswer = document.querySelector("#" + elName).value;
var stAnswerGiven = stAnswer.toLowerCase();
var stAnswerExpected = strWord.toLowerCase();
if (stAnswerGiven == stAnswerExpected){
divAnswer.style.color = "#0F0";
divAnswer.innerHTML = "Correct";
}else{
divAnswer.style.color = "#F00";
divAnswer.innerHTML = "Wrong";
}
}
function funNewQuestion(){
var intRandomQNum = parseInt(Math.random() * arrSpanishWords.length);
var elDisplayQuestion = document.getElementById("divWord");
divAnswer = document.getElementById("divAnswerIs");
divAnswer.innerHTML = "";
elDisplayQuestion.innerHTML = arrSpanishWords[intRandomQNum];
strWord = arrEnglishWords[intRandomQNum];
}
document.addEventListener("DOMContentLoaded", funNewQuestion(), false);
Word: <div id="divWord"></div><div id="divAnswerIs"></div>
Answer: <input type="text" id="frmTxtAnswer">
<button id="check" onclick="funCheck('frmTxtAnswer')">Check Answer</button>
<button id="check" onclick="funNewQuestion()">Next Question</button>

How to get the -real- last character typed in input with maxlength?

I wanted to know which character the user is typing into an input:
I have an input:
<input maxlength="20"/>
and a script that returns the last typed char:
var eingabe;
$('form').on('keypress', function(event) {
/// if no whitespace:
if (String.fromCharCode(event.keyCode).replace(/\s/g, "").length > 0) {
eingabe = String.fromCharCode(event.keyCode);
$('#eingabe').html("<div>Eingabe : "+ eingabe +"</div>");
}
});
My question is:
because my input has a maxlength attribute, the last typed character on the keyboard is sometimes not the last -real- typed character into the input because the input is "full". How can I get the last character typed into the input?
I haven't tried it, but it must work...
Set onkeypress= or onkeydown= on the Input element and store the key value in a LastChr variable.
I had a similar problem. I wanted to call a function if the user types a specific character into my input field. I solved it with the following:
var input = document.getElementById('myInput');
input.addEventListener('input', function() {
// Get cursor position
var start = this.selectionStart;
// Get last typed character
var lastChar = String.fromCharCode(this.value.charCodeAt(start - 1));
if(lastChar === '[YOURCHARHERE]') {
// do something
}
});
Please keep in mind, that 'input' is only supported down to IE8, but if you don't care about a proprietary browser, you should be fine. I hope this helps.
Inside your function, use the value of the input element to get the last character like $('#input_field').val().substr($('#input_field').val().length - 1) or use your best coding skill to accomplish something similar without accessing the field twice, wink wink.
Use keyup instead:
$('form').on('keyup', function(event) {
var cursorPos = event.target.selectionStart;
var lastTypedChar = elem.target.value[cursorPos - 1];
});

Javascript/Jquery validating decimal input on keyup

I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after . (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />
<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
val = re1.exec(val);
//console.log(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
</script>
Thanks
How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g
In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.

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