Javascript Approved Number in RegExp [duplicate] - javascript

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 8 years ago.
I'm trying to change a value user enters to a true number (ex. 15 or 144.38). If it has unapproved characters (ex. $,) then they should be stripped. Also if user enters value with multiple periods (ex. 43.14.14) then I want to clear entire value. I was able to do step 1 but can't figure step 2, please advise. Here's my code so far
http://jsbin.com/otawiVa/1
function myFunction()
{
var str = document.getElementById("number_field").value;
var res = str.replace(/[^0-9.}]/g,"");
document.getElementById("approved_number").innerHTML=res;
}

change your function to
function myFunction()
{
var str = document.getElementById("number_field").value;
var res = str.replace(/[^0-9.}]/g,"");
if (res.indexOf('.') !== res.lastIndexOf('.')) {
document.getElementById("approved_number").innerHTML="";
} else {
document.getElementById("approved_number").innerHTML=res;
}
}
Example here:
http://jsbin.com/UNOHoYek/1

See http://jsbin.com/OKoJuloQ/3/ for a possible answer.
Changing user input without providing feedback is probably not a good idea.
Better to just handle what can be taken as a number and report the rest.
window.alert is just one way to report it.
The important bits are the conversion to Number and testing against NaN.
CODE (also available via link above)
<!DOCTYPE html>
<html>
<body>
<input type="text" value="" id="number_field">
<button onclick="myFunction()">Submit</button>
<p id="approved_number"></p>
<script>
function myFunction() {
try {
var str = document.getElementById("number_field").value;
// var res = str.replace(/[^0-9.}]/g,"");
var res = str;
if (Number.isNaN(Number(res))) {
window.alert(res + " is not a number (NaN)\nOnly digits, decimal point,\nand exponent (e.g. 3.2e4) are allowed");
} else {
document.getElementById("approved_number").innerHTML=Number(res).toString(10);
}
} catch (exception) {
window.alert(exception);
}
}
</script>
</body>
</html>

Related

I'm comparing two variables in an IF statement but I'm getting wrong results [duplicate]

This question already has answers here:
javascript comparison of strings
(4 answers)
Closed 1 year ago.
I tried this code and when running for the first time i clicked start and i got me the result "1 is smaller than 2" whick is right but after changing the first input to 10 and clicking start again, it still showed "10 is smaller than 2". Am I doing something wrong here?
<textarea type="number" id="one">1</textarea>
<textarea type="number" id="two">2</textarea>
Start
<p id="demo"></p>
<script>
function start() {
var numberOne = document.getElementById('one').value;
var numberTwo = document.getElementById('two').value;
if(numberOne>=numberTwo) {
document.getElementById('demo').innerHTML = numberOne + ' is bigger than ' + numberTwo;
}
else {
document.getElementById('demo').innerHTML = numberOne + ' is smaller than ' + numberTwo;
}
}
</script>
You are comparing strings, not numbers.
use parseInt or parseFloat to convert it to a number.
var numberOne = parseFloat(document.getElementById('one').value);
Yes it is expected, input in DOM always string even if the type is number.
parse them to number first before comparing.
const intOne = parseInt(numberOne, 10);
const intTwo = parseInt(numberTwo, 10);
// compare them
if (intOne >= intTwo) {
// do your thing
}
Edit: Update code by #Sebastian Simon suggestion

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>

Enter a three digit number and write a function that adds the numbers together - Homework Warning

I have this homework problem with functions. I can get the user's string input into an array of numbers, but I cant figure out how to then add them. I tried doing a for loop but this seems like Im going down the wrong path.
Question:
Allow a user to enter a three digit number.
Write a function that adds the numbers together.
Hint #1: You need to turn a string into an integer.
Hint #2: Strings can be treated as arrays too.
Here is my code:
document.getElementById('submitBtn3').addEventListener
("click", function ()) {
var digits = document.getElementById('digits').value;
var digitsArray = digits.split(',').map(function(i) {
return parseInt(i, 10);
})
console.log(digitsArray);
document.getElementById('q11').innerHTML = digitsArray;
})
Any help appreciated
function add(a, b) {
return a + b;
}
document.getElementById('submitBtn3').addEventListener("click", function() {
var digits = document.getElementById('digits').value;
var sum = digits.split("").map(function(n){return parseInt(n)}).reduce(add,0);
document.getElementById('q11').innerHTML = sum;
});
<input id="digits" type="number"/>
<button id="submitBtn3">go!</button>
<div id="q11"></div>
You have some issues,
a closed parenthesis without the following block for the function
("click", function ())
// ^
splitting with split(','), which works only for joint arrays, like 1,2,3, but not with a string, without commas. You need here an empty string split('').
Now you can add the single numbers in another loop, or extend the first loop with an addition.
document.getElementById('submitBtn3').addEventListener("click", function() {
var digits = document.getElementById('digits').value;
var digitsArray = digits.split('').map(function(i) {
return parseInt(i, 10);
});
console.log(digitsArray);
document.getElementById('q11').innerHTML = digitsArray;
});
<input id="digits">
<button id="submitBtn3">go!</button>
<div id="q11"></div>
Just a hint for completeness.
Strings have a length property. This helps to iterate through a string with a loop of choice. The access inside could be with String#charAt or with brackets and an index, like string[index].
This one might be more homework answer friendly than using a 1 line .map
function myFunc() {
var num = document.getElementById('digits').value;
var tot = 0;
num.split('').forEach( function (x) {
tot = tot + parseInt(x,10);
});
document.getElementById('output').innerHTML = tot;
}
<input id="digits" />
<button onClick="myFunc()">Submit</button>
<div id="output"></div>

JQuery: Getting number from html element and alter it in Jquery/Javascript

I have some number printed on my html for special usage, therefore i need to grab it from html, alter it in javascript and output again.
So i have few numbers like below in my HTML:
<p id="usage">6564</p>
and i'd like to have a if statment in order do some modifcation of "6564",
below is some pseudo codes, which tells what i'd like to do.
var checker = $("#usage").html();
if(checker >= 2 digits){
//display the first two digits
}
else {
$("#usage").html("1");
}
The if statement should display the first two digits only, if the number has more than 2 digits otherwise it will return "10", So the result should be "65"
Solution :
For people who experience the same issues as me
var checker = $(".totalPage").text().replace(/,/g, ""); //it you have comma between your number like 6,545
var pagevalue = parseInt(checker.slice(0,2));
if(checker.length >= 2){
$(".totalPage").text(pagevalue+1);//you can modify the our put even further
}
else {
$(".totalPage").text("10");
}
var checker = $("#usage").text();
if(checker.length >= 2){
$("#usage").text(checker.slice(0,2));
}
else {
$("#usage").text("10");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="usage">6564</p>
Use slice to get the 2 digits.
Use length to tell if number has more than 2 digits
Here's the pure Js version.
function extractFunction() {
var checker = document.getElementById("usage").innerHTML;
if (checker.length > 2) { //if cheacker lentgh > 2
var result = checker.substr(0, 2); //start at char 1 and pull first 2 chars
document.getElementById("usage").innerHTML = result;
}
else{
document.getElementById("usage").innerHTML = "1";
}
}
<p id="usage">6564</p>
<button onclick="extractFunction()">Extract it</button>

How can I adapt this javascript to return a postcode less the last 2 characters? [duplicate]

This question already has answers here:
How do I chop/slice/trim off last character in string using Javascript?
(25 answers)
Closed 7 years ago.
function() {
var address = $("#postcode").val();
var postcode = address.split(' ');
postcode = "Postcode:"+postcode[(postcode.length-2)];
return postcode;
}
This js pulls a postcode value from an online form when the user runs a query. I need to know how I get it to deliver the postcode less the last 2 characters. for example, SP10 2RB needs to return SP102.
Use substring() or substr() or slice().
You have to slice the string and return what you want:
return postcode.slice(0, -2);
// example
postcode = "sample";
// output
"samp"
You can use this function:
function postCode(address)
{
var tmpAddr = address.replace(' ','');
tmpAddr = tmpAddr.substr(0, tmpAddr.length-2);
return tmpAddr;
}
alert(postCode('SP10 2RB'));

Categories

Resources