Javascript - Howcome .length won't detect the "t" - javascript

To summarize, for my program, I want to be able to detect the 't', and prevent the user from adding something with a quantity of '3t', '3t3', or anything of that matter.
In other words, if the quantity starts with a number, but has letters in it, it will still go through and be added, which is what I DON'T WANT.
Here's the code for where I add things. Is there any approach I should do differently?
function addProduct(){
var input = document.getElementById("productName").value;
var input2 = document.getElementById("cost").value;
var input3 = parseInt(document.getElementById("quantity").value);
var s_input3 = input3.toString();
var table = document.getElementsByTagName('table')[0];
if (isNaN(input2) || input2<0)
{
alert("not a number");
return(-1);
}
if (isNaN(input3) || input3<0)
{
alert("not a number");
return(-1);
}
// MY ATTEMPT OF DETECTING THE 't'
for (i = 0; i < s_input3.length; i++)
{
console.log(s_input3.length)
if(!(isNaN(s_input3[0]) && isNan(s_input3[i])))
{
alert("not a number")
return(-3)
}
}

You don't have to go through each of the character in the string. You can just do isNaN() on the input value.

The isNan() function does work on 3t as this code example shows. It might seem initially counter intuitive as a double negative, but the global function tests 'is not a number' so a number is false and a string true. Try code example below.
<html>
<body>
<p id="testOutput"></p>
<button onclick="testNumber()">Test is number</button>
<script>
function testNumber() {
var output = "";
 output= output + isNaN('3t') + ": 3t<br>";
 output = output + isNaN(3) + ": 3<br>";
document.getElementById("testOutput").innerHTML = output;
}
</script>
</body>
</html>
Output is:
true: 3t
false: 3
W3Schools Ref

Related

Why can't println(); be used as a variable?

I'm fairly new to Javascript, and am confused on something. Why can't the command "println("..."); be called as a variable such as: var num = println("...");. I could be wrong, and if you are able to, I'd be happy to know how. But after some testing it seems like I can't. My test code is:
function start() {
var SENTINEL = "1 1";
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = println(rollOne + rollTwo);
if(num == SENTINEL) {
println("You did it");
}
}
All it's supposed to do is give to random numbers in a # # form and, if it sees that the numbers are 1,1, it will give a message. It wont give the message and can't seem to view the variable "num" as an actual variable. But when I change the variable num to simply asking the user for a number:
function start() {
var SENTINEL = -1;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = readInt("Enter number");
if(num == SENTINEL) {
println("You did it");
}
}
And type in -1, it triggers the sentinel, thus promptly displaying the message. This is a really roundabout way to ask a simple question but I hope I can get some help. Thank you :)
Why can't the command "println("..."); be called as a variable such as: var num = println("...");
[...] It wont give the message and can't seem to view the variable
If the value returned is unusable, it is most likely undefined; i.e. The function println doesn't explicitly return anything.
In your case, you could try something like this:
var printInt = function(num) { println(num); return num; }
Note, println isn't part of the standard JavaScript language. For modern web browsers, it can be adapted to use (console.log(...)).
var printInt = function(num) { console.log(num); return num; }
And then to adapt to your code:
var num = printInt(rollOne + rollTwo);
But this still won't validate because you're comparing against "1 1" whereas your logic will return 2. JavaScript (as well as many other languages) implicitly uses addition when supplied with two numbers, but concatenation when supplied with at least one string.
var SENTINEL = "1 1"; // <---- String!
var SENTINEL = -1; // <---- Number!
So you should consider something like this instead (renamed accordingly):
var printRolls = function(text) { println(text); return text; }
var rolls = printRolls(rollOne + " " + rollTwo);
if(rolls == SENTINEL) {
println("You did it");
}
Or to simplify it a bit:
if(printRolls(rollOne + " " + rollTwo) == SENTINEL)
println("You did it");
It is possible that println doesn't return the string that is passed into. In that case, you can use
if (SENTINEL === rollOne + " " + rollTwo)
to format the string and properly test equality.
In JavaScript it is possible to assign the return value from any function to a variable similar to how you've done it:
var anyVariable = anyFunction();
But, some functions return the value undefined. Or they return a number, or an array, or...whatever.
I imagine your println() function prints the value you pass to it somewhere (on the screen? to the console?) and then returns undefined. Or if it is returning the printed value it is in a format different to what you have used in your SENTINEL variable. So then when you try to compare that with SENTINEL it won't be equal.
To fix your original function, assign the sum of the rolls to a variable, then print and test that:
function start() {
var SENTINEL = 2;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = rollOne + rollTwo;
println(num);
if(num == SENTINEL) {
println("You did it");
}
}
EDIT: if you want the println() to display a string like "1 1" or "3 5" to show what each of the two rolls were then do this:
println(rollOne + " " + rollTwo);
That is, create a new string that is the result of concatenating rollOne's value with a single space and then rollTwo's value.

Math Input, Calculate, and Output Javascript with Fractions/Decimals

I was wondering if it was possible for a program in Javascript to receive fractions as input and use these fractions to calculate certain values. I have attempted to make a calculator of percentage difference (physics) which uses the formula ((|max-min|)/((max+min)/2))*100. I already understand how to manipulate the input and split it in an array. As such, I stored the max and min values in val1 and val2. However, the issue comes with the computation. Originally I clumped the whole formula in a single statement, but it didn't work. Thus, I separated the calculations into steps and stored the value in variables after each step to make sure it did the computations properly. This is what I have:
var step1=Math.abs(val1-val2);
var step2=val1+val2;
var step3=step2/2;
var step4=step1/step3;
var final=Math.round(step4*100*100)/100;
However, there are still a lot of glitches going on with the computations, especially with fractions and decimals. For example, the percentage value when 90/100 and 89/100 are inputted would be FAR different from if 9/10 and 89/100 are placed. Occassionally, inputting decimals return NaN. I really don't understand what's going on. Anyone who can highlight what's wrong with the above code in computing percentage difference or teach me how Javascript computes and show how the computations are in line with the outputs I receive would definitely help.
Thank You. :)
If it's any help, this is the full code of the program. You can ignore this if it isn't necessary in solving the problem. I've deleted all completely unnecessary parts of the code to the problem.
<html>
<head>
<title></title>
</head>
<style type="text/css">
</style>
<script>
var def;
function submit() {
var e = document.getElementById("topic");
var ter = document.getElementById("term").value;
var strUser = e.options[e.selectedIndex].value;
if (!strUser) {
document.getElementById("textcom").value = "Please specify what needs to be solved.";
}
else if (!term) {
document.getElementById("textcom").value = "Please specify the values used to calculate.";
}
else {
if (strUser == "a") {
var arr = ter.split(",");
var val1 = parseInt(arr[0]);
var val2 = parseInt(arr[1]);
if (arr.length > 2 || arr.length < 2) {
def = "Error. Incorrect number of values written.";
}
else if (isNaN(val1) || isNaN(val2)) {
def = "Error. One or more values input is/are not a number.";
}
else {
var step1 = Math.abs(val1 - val2);
var step2 = val1 + val2;
var step3 = step2 / 2;
var step4 = step1 / step3;
var final = Math.round(step4 * 100 * 100) / 100;
def = final + "%";
}
}
document.getElementById("textcom").value = def;
}
}
</script>
<body>
<h1>Physics Calculator</h1>
<span>Please choose desired solution:</span>
<select id="topic">
<option disabled selected value>------ Option ------</option>
<option value="a">Percent Difference</option>
</select>
<br>
<span>Values:</span>
<input type="text" id="term"></input>
<br>
<br>
<textarea rows="20" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
<br>
<button onclick="submit()">Submit</button>
<script>
document.getElementById("textcom").readOnly = "true";
</script>
</body>
</html>
It seems like you expect JavaScript to recognise fractions like 12/100 as numerical values when applying parseInt to them.
This is not the case because:
A division (/) is an operator in JavaScript (and most other languages), not a numerical notation (like the decimal .). Characters like / are not allowed in numerical literals.
Even if you enter numbers as decimals (like 15.89), the function parseInt will ignore the decimal parts -- the name of parseInt already reveals this behaviour. You should use parseFloat, or shorter, apply the unitary + to the string, which implicitly converts it to a number.
To solve this, you could write a function that turns fractional notations into the numbers they represent. I have called that function evaluate in the snippet below:
// To interpret fractions (with '/') as numbers:
function evaluate(term) {
// remove spaces and get numerator and denominator
var arr = term.replace(/ /g, '').split('/');
// get part before '/' and turn into number
var val = +arr.shift();
// read denominator(s) and perform division(s)
while (arr.length) {
val = val / +arr.shift();
}
return val;
}
function submit() {
var e = document.getElementById("topic");
var ter = document.getElementById("term").value;
var strUser = e.options[e.selectedIndex].value;
var def;
if (!strUser) {
def = "Please specify what needs to be solved.";
}
else if (!term) {
def = "Please specify the values used to calculate.";
}
else if (strUser == "a") {
var arr = ter.split(",");
var val1 = evaluate(arr[0]);
var val2 = evaluate(arr[1]);
if (arr.length !== 2) {
def = "Error. Incorrect number of comma-separated values written; two expected.";
}
else if (isNaN(val1) || isNaN(val2)) {
def = "Error. One or more values input is/are not a number.";
}
else {
var step1 = Math.abs(val1 - val2);
var step2 = val1 + val2;
var step3 = step2 / 2;
var step4 = step1 / step3;
var final = Math.round(step4 * 100 * 100) / 100;
def = final + "%";
}
}
document.getElementById("textcom").value = def;
}
<span>Please choose desired solution:</span>
<select id="topic">
<option disabled selected value>------ Option ------</option>
<option value="a" selected>Percent Difference</option>
</select>
<br>
<span>Values:</span>
<input type="text" id="term"></input>
<br>
<br>
<textarea readonly rows="3" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
<br>
<button onclick="submit()">Submit</button>
NB: note that you can use the readonly attribute in HTML -- no need to set this via JavaScript.

Need to get indexes from array and output them to user in JavaScript

We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;

javascript: counting digits in a text input

I have a piece of HTML that creates a web form with three text fields (name, group and number), all of which are validated using JavaScript to check that there is data inputted into them. In the last text field, I need to introduce an additional bit of JavaScript to check that the data inputted by the user is also four digits long (for example 2947 or 94Q3). As a complete JavaScript novice, I'm not sure how I would do this! Would I have to create a variable that could take the value of the inputted data, then count the digits of the variable, or could I do it directly from the field? Here is the Javascript section of my code:
function validateForm() {
var result = true;
var msg = ””;
if (document.Entry.name.value == ””) {
msg += ”You must enter your name\n”;
document.Entry.name.focus();
document.getElementById(‘name’).style.color = ”red”;
result = false;
if (document.Entry.group.value == ””) {
msg += ”You must enter the group\n”;
document.Entry.group.focus();
document.getElementById(‘group’).style.color = ”red”;
result = false;
}
if (document.Entry.number.value == ””) {
msg += ”You must enter the number\n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color = ”red”;
result = false;
}
if (msg == ””) {
return result;
} {
alert(msg)
return result;
}
}
If possible, could you tell me what code I would need to insert? Thank you!
Place this block in your conditions list:
if (document.Entry.number.length!=4) {
msg+=”You must enter 4 digits \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
if (document.Entry.number.value==””) {
msg+=”You must enter the number \n”;
document.Entry.number.focus();
document.getElementById(‘number’).style.color=”red”;
result = false;
}
change this to
if (document.Entry.number.length != 4){
msg+="Number must be exactly 4 characters \n";
document.Entry.number.focus();
document.getElementById('number').style.color="red";
result = false;
}

Insert space after certain character into javascript string

I'm working on a form and I'd like to mask the input of the phone numbers. The plugins what I found aren't okay for me since the area code could be 1 or 2 character long.
What I'd like to do is the following:
when the user types his number after the first two character the script inserts a space on keyup, then after the next three and later after every fourth character.
So when someone types 44444444444 then in the textbox appears 44 44 444 4444.
I must check the second group as well, and when someone types there for example 1, the the number must look like: 44 1 444 4444
Is any solution to do that?
You could do something like this:
http://jsfiddle.net/ffwAA/4/
Which applies this function to the string to get the desired formatting:
function formatCode(str){
var result = str;
str = str.replace(/\D+/g, "");
var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/);
if(m){
result = m[1] + " ";
if(m[2]) result += m[2] + " ";
if(m[3]) result += m[3] + " ";
if(m[4]){
result += m[4].split(/(\d{4})/).join(" ");
result = result.replace(/\s+/g, " ");
}
}
return result;
}
And using this jQuery to set it up:
function update(obj){
var val = obj.value;
var got = formatCode(val);
if(got != val)
obj.value = got;
}
var timer;
var prev_val = "";
$('#code').keyup(function(){
clearTimeout(timer);
// when adding numbers at the end of input, update at once
// don't want to update when editing in the middle of the string or removing parts of it
// because it would move the carret location to the end of input, and make it unusable
if(this.value.indexOf(prev_val) == 0){
update(this);
prev_val = this.value;
return;
}
prev_val = this.value;
// in other cases update 1 second after the changes are done
timer = setTimeout(update, 1000, this);
});
Have you tried the maskedInput plugin?
http://digitalbush.com/projects/masked-input-plugin/
I think it can solve your problem.
Hope this helps. Cheers

Categories