Condition for a number to be in range - Titanium/Javascript - javascript

I'm developing app in Titanium using Javascript and trying to realize the following check logic:
User has entered one value in range between 1 and 200, then he/she should enter second value in range between 1 and the first value(less or equal, but no more then the first value).
Here is my code:
var value_alert = ''; //First value
var value_remind = ''; //Second value (should be less or equal)
var default_value_alert = 10; //Default first value for TextField
var default_value_remind = 5; //Default second value for TextField
// handle and save the first value entered by user
function doOpenAlert(){
var input_text = Ti.UI.createTextField({
keyboardType: Ti.UI.KEYBOARD_PHONE_PAD
});
if(value_alert === ''){
input_text.value = default_value_alert;
} else {
input_text.value = value_alert;
}
var dialog = Ti.UI.createOptionDialog({
title : "Specified distance in the range 1-200 km",
androidView : input_text,
buttonNames : ['Ok', 'Cancel']
});
dialog.show();
dialog.addEventListener('click', function(e){
if(value_remind === ''){
value_remind = default_value_remind;
}
if(e.index == 0){ // Check is Ok pressed
// check_number = isInt(input_text.value);
if(input_text.value >= 1 && input_text.value <= 200){ // Check that the first value is in range
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Distance is " + input_text.value + " km."
});
toast.show();
value_alert = input_text.value; // Saving the first value entered by user
} else if(input_text.value == 0){
alert("The field is empty.");
} else if(!(input_text.value >= 1 && input_text.value <= 200)){
alert("Range is between 1 and 200 km.");
}
}
});
}
// handle and save the second value entered by user
function doOpenMinne(){
var input_text = Ti.UI.createTextField({
keyboardType: Ti.UI.KEYBOARD_PHONE_PAD
});
if(value_remind === ''){
input_text.value = default_value_remind;
} else {
input_text.value = value_remind;
}
var dialog = Ti.UI.createOptionDialog({
title : "Remind before number",
androidView : input_text,
buttonNames : ['Ok', 'Cancel']
});
dialog.show();
dialog.addEventListener('click', function(e){
if(value_alert === ''){
value_alert = default_value_alert;
}
if(e.index == 0){
// check_number = isInt(input_text.value);
if(input_text.value >= 1 && input_text.value <= value_alert){ // Check if the second value in is range between 1 and the first value
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Remind at " + input_text.value + " km."
});
toast.show();
value_remind = input_text.value; // Saving the second value entered by user
} else if(input_text.value == 0){
alert("The field is empty");
} else if(!(input_text.value >= 1 && input_text.value <= 200)){
alert("The range is between 1 and 200 km");
}
}
});
}
For example, it works well in the following combination:
1)
First value - 10;
Second value - 5;
2)
First value - 105;
Second value - 101;
And the main thing, if the first value is >= 100 , but the second is < 100 - it doesn't work.
It seems that conditions are correct, but works incorrect - can't find a mistake.

I think that the issue you're having is that you're comparing the values as strings rather than numbers. When you compare two strings, Javascript bases the comparison on the Unicode values of the characters in order. What does that mean for you? The short answer is, that while "90" < 200 is true because that comparison results in the "90" being coerced to 90, "90" < "200" is false because "9" is greater than "2".
In order to avoid this behavior, you need to convert one or both of your variables to numbers. This answer on converting strings into numbers shows a number of ways for you to do that, but in your case, I think that parseInt(input_text.value, 10) <= parseInt(value_alert, 10) would work fine for you.

Related

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

Updating display on JS calculator

I want to have my calculator to display "0" when cleared or no other numbers have been entered but when I start adding numbers I want the 0 to be replaced. Currently when I enter any number it replaces the number on the display to the number entered.
this.currentDisplay = "0"
numberData(number) {
if (number === "." && this.currentDisplay.includes("."))
return
if (this.currentDisplay = "0") {
this.currentDisplay = this.currentDisplay.toString().replace("0", number.toString())
}
else {
this.currentDisplay = this.currentDisplay.toString() + number.toString()
}
}
You have an error on the this condition:
if (this.currentDisplay == "0") {
...
}
In your code you are assigning this.currentDisplay = 0, you should compare with == or better === to compare the types of the variables too.

How to sanitize (digits and hyphen only) and auto-format (hyphen and leading zeros insertion) a text input value while typing and/or pasting text?

There are similar questions on SO, but mine is a bit unique. I want to limit an input text field to 9 characters in length (currently solved with maxlength attribute), only allow typing in numeric values and the hyphen character. Sort of handled with this code returning "True":
/^\d*\-?\d*$/.test(value)
Where I'm stuck is, I want the input text field to auto-format the value as the user types in the format:
12345-123
Where it's 5 digits (may have leading zeros or not depending on how user inputs it), followed by a hyphen, then always 3 digits. I'd like it to pad the first 5 with zeros if user enters something like "123-495" manually, so it would become "00123-495".
I'm not sure how to add in the auto-zero padding, or placement of the hyphen automatically.
Not opposed to using jQuery, but would prefer vanilla.
EDIT: Thought it might be useful to add. This is for an access card number entry box. So value will always be a positive number, and will always have 3 digits after the single hyphen. The card number will always be 5-digits in length, but again, may be padded with zeros to make it that length. Ideal output should always be "xxxxx-xxx".
EDIT 2: This seems to work, but there's an issue where user can enter non-numeric characters at first and after the 1st entry, only then does it clear it out. It also doesn't seem to let me hit backspace past the hyphen... Is there a way to prevent it from allowing alpha characters completely?
// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
// Current value
new_val = '';
if (this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
console.log("Value not hyphenated yet");
pad_needed = 5 - this.value.indexOf('-');
console.log('Pad needed: ' + pad_needed);
new_val = this.value.padStart(9, '0');
this.value = new_val;
} else if (this.value.length >= 5 && this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
if (this.value.slice(5, 1) == '-') {
// Already a hyphen added, just add rest of numbers
new_val = this.value.slice(0, 6) + this.value.slice(6);
} else {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
}
this.value = new_val;
} else if (this.value.length >= 5 && !this.value.includes('-')) {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
this.value = new_val;
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
setInputFilter(document.getElementById("card-number"), function(value) {
return /^\d*\-?\d*$/.test(value); // Allow digits and '-' only
});
function getSanitizedInputValue(value) {
value = value
.trim()
.replace(/^[-]+/, '')
.replace(/[-]+/, '-');
let [
first,
...rest
] = (value.match(/[-\d]+/g) ?? [])
.join('')
.split('-')
let joiner = '';
if (first.length >= 6) {
joiner = '-';
rest.unshift(first.slice(5));
first = first.slice(0, 5);
} else if (rest.length >= 1) {
joiner = '-';
first = first.padStart(5, '0');
}
return [
first,
rest.join(''),
]
.join(joiner)
.slice(0,9);
}
function handleInput({ currentTarget: control }) {
const { value: recentValue, selectionStart, selectionEnd } = control;
const regXHasHyphen = /-/;
const sanitizedValue = getSanitizedInputValue(recentValue);
const sanitizedLength = sanitizedValue.length;
const recentLength = recentValue.length;
const positionDelta = (
(recentLength <= 5) &&
(sanitizedLength >= 6) &&
(sanitizedLength - recentLength)
) || (
!regXHasHyphen.test(recentValue) &&
regXHasHyphen.test(sanitizedValue) &&
1
) || 0;
control.value = sanitizedValue;
control.selectionStart =
Math.min(sanitizedLength, (selectionStart + positionDelta));
control.selectionEnd =
Math.min(sanitizedLength, (selectionEnd + positionDelta));
}
document
.querySelector('[type="text"]')
.addEventListener('input', handleInput);
<input type="text" maxlength="9" />

Input number output corresponding value

Given these 9 words, display on the page the word corresponding to their chosen number
1.mercury
2.venus
3.earth
4.mars
5.jupiter
6.saturn
7.uranus
8.neptune
9.pluto
Im not sure what I'm missing here Ive done a lot of trial an error and nothing seems to work.
I've tried using numEntry as my comparison for all the if statements and it hasn't worked. When I made var numEntry = true; only Mercury would display. When I made var numEntry = 1,2,3,4,5,6,7,8,9 only pluto would show. I then tried to create a variable for each number and use each once in a comparison like below but every planet shows up instead of the corresponding number to planet.
var numberOfPlanet = prompt("Please enter a number between 1 and 9");
function thePlanets(){
var numOne = 1;
var numTwo = 2;
var numThree = 3;
var numFour = 4;
var numFive = 5;
var numSix = 6;
var numSeven = 7;
var numEight = 8;
var numNine = 9;
//do I need to define numberEntry if I use it in my comparisons below? what do I define it as after the = //// I tried defining as true but only mercury will appear, i tried inserting numbers 1 through 9 but only pluto worked//
if(numOne = 1 ){
document.write("mercury");
}
if(numTwo = 2 ){
document.write("venus");
}
if(numThree = 3 ){
document.write("earth");
}
if(numFour = 4 ){
document.write("mars");
}
if(numFive = 5 ){
document.write("jupiter");
}
if(numSix = 6 ){
document.write("saturn");
}
if(numSeven = 7 ){
document.write("uranus");
}
if(numEight = 8 ){
document.write("neptune");
}
if(numNine = 9 ){
document.write("pluto");
}
}
thePlanets();
I just need a number to correspond with the right planet when the user enters that number eg. ( user enters 1 and it displays mercury)
Some notes:
Use numberOfPlanet as the function argument to compare with (it becomes num inside the function).
Convert numberOfPlanet to Number as prompt() returns string.
Use === (strong comparison) instead of = (assignment).
Use else if instead of next if if you need only one variant from some so that the comparing stops when the right result is found.
var numberOfPlanet = Number(prompt("Please enter a number between 1 and 9"));
function thePlanets(num){
if(num === 1){
document.write("mercury");
}
else if(num === 2){
document.write("venus");
}
else if(num === 3){
document.write("earth");
}
else if(num === 4){
document.write("mars");
}
else if(num === 5){
document.write("jupiter");
}
else if(num === 6){
document.write("saturn");
}
else if(num === 7){
document.write("uranus");
}
else if(num === 8){
document.write("neptune");
}
else if(num === 9){
document.write("pluto");
}
}
thePlanets(numberOfPlanet);

Set variable to itself plus another variable in JavaScript

I made a more complex (albeit only slightly) program in my CS class that ran some calculation and discounts according to some rules. It was written in Java, and read and output to a file. I am trying to redo it in JavaScript with a loop taking in input and applying calculations afterwards. I would call both functions after the second while loop closes.
My problem is that priceCount increments by price perfectly, while qty seems to just spit out somewhat random numbers (they're all multiples of inputs, however) with a leading 0. What's going on here? It's the exact same logic as the priceCount, but simply isn't working. I tried moving variables around, thinking it's a scope issue, but nothing worked.
I hope I'm not asking a question that has been answered many times. I tried searching extensively, but that is a skill in itself, and it is difficult for me to phrase my question into keywords. Any and all input will be greatly appreciated.
function discountCalc (price, amount) {
var discount;
if (amount <= 30){
discount = oldPrice * 0.05;
}
else if (amount >= 30 && amount <= 50){
discount = oldPrice * 0.1;
}
else if (amount >= 51 && amount <= 75){
discount = oldPrice * 0.25;
}
else {
discount = oldPrice * 0.4;
}
return discount;
}
function adjust(newPrice, amount){
var adjust;
if (newPrice < 500){
adjust = -20;
}
else if (newPrice >= 500 && amount < 50){
adjust = newPrice * 0.05;
}
else{
adjust = 0;
}
return adjust;
}
var answer = "new", price, amount, customer = 1;
while (answer !== "quit" && answer !== "Quit" && answer !== "q" && answer !== "Q") {
console.log("invoice # 000" + customer);
if (answer == "new" || answer == "New") {
customer = customer + 1;
var another = "yes";
var priceCount = 0;
var qty = 0;
while (another == "yes" || another == "Yes" || another == "y" || another == "Y"){
price = prompt("price?");
amount = prompt("amount?");
qty = qty + amount;
priceCount = priceCount + (price * amount);
console.log("Price: " + price + " Amount: " + amount);
another = prompt("type yes for another, any key to stop");
}
console.log("Total price is: " + priceCount);
console.log("Total items: " + qty);
priceCount = 0;
qty = 0;
}
answer = prompt("new or quit?");
}
console.log("thanks");
Prompt returns a string, so you should convert it to a number.
You can use parseInt(), parseFloat(), or Number().
parseInt() returns an integer value, and parseFloat() returns a float.
Number() can return both, but if the prompt returns string that doesn't evaluate to numbers, it returns NaN. It can be useful to check if the user is giving invalid data.
So replace
qty = qty + amount
to
qty = qty + Number(amount) //or parseInt(amount), parseFloat(amount)
if you have other areas adding amount to a number, you can do the same.

Categories