It gives always answer "Hello City" although i pressed 1 and 2.. what is wrong with the code? what is better to use ? if else statement or switch statement?
anyone can help?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function number()
{
var number;
number=document.getElementById('m').value;
switch (number)
{
case 1:
day="Hello World";
break;
case 2:
day="Hello Asia";
break;
default :
day="Hello City";
}
document.write(day);
}
</script>
<input type="number" name="" id="m">
<input type="submit" name="Click" onclick="number()">
</body>
</html>
Cast the value explicitely to a number otherwise it will be a string, the Switch statements in Javascript always use strict type checking (===), thus your example will always return the default value.
var number= +document.getElementById('m').value;
What about parse to integer.
var number=parseInt(document.getElementById('m').value)
Switch testing strict quality. So there is used triple equals.
Related
I am a beginner javascript programmer. I made a very simple program to multiply 2 numbers with textbox. At first it worked. But then I wrote some logic to avoid some bugs. And some of the logics are not working. could anybody take a look at this code and tell me what's wrong here:
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=document.getElementById('text1').value;
text1 = Number(text1);
text2=document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if(isNaN(text1)||isNaN(text2)){
document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if(text1.length>0 && Number.isInteger(text1)==false && text2.length>0 && Number.isInteger(text2)==false){
document.getElementById('P').innerHTML='You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if(text1.length==0||text2.length==0){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
let ans=BigInt(text1*text2);
document.getElementById('P').innerHTML=ans;
document.getElementById('zero').innerHTML='×';
}
}
I am getting the correct output when i enter the integer values in the text box and click submit button. But the problem is both the else if statement is not working. when i give the input as a float value it is not doing anything. It has to display the message , but it is not. same when i dont give any input and click the submit button. It is not displaying the message. Why does this happen. How to solve this?
HTML of this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</body>
</html>
You used double equal signs and not triple. in order to check for strict equality.
now it works:
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick = () => {
text1 = document.getElementById('text1').value;
text1 = Number(text1);
text2 = document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if (isNaN(text1) || isNaN(text2)) {
document.getElementById('P').innerText = 'it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if (!(text1.length > 0 && Number.isInteger(text1)) && !(text2.length > 0 && Number.isInteger(text2))) {
document.getElementById('P').innerHTML = 'You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if (text1.length === 0 || text2.length === 0) {
document.getElementById('P').innerHTML = 'you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else {
let ans = BigInt(text1 * text2);
document.getElementById('P').innerHTML = ans;
document.getElementById('zero').innerHTML = '×';
}
}
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
This should work. There is no length property available in Number. So if you cast your inputs to Number, inputValue.length will no longer work.
let text1;
let text2;
let ans;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=document.getElementById('text1').value;
text1 = Number(text1);
text2=document.getElementById('text2').value;
text2 = Number(text2);
// checking if it is a number or not
if(isNaN(text1)||isNaN(text2)){
document.getElementById('P').innerHTML='it should be a number. Not alphabets or symbols';
}
// checking if it is an integer or not.
else if(!Number.isInteger(text1) || !Number.isInteger(text2)){
document.getElementById('P').innerHTML='You cant multiply with decimal points';
}
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
else if(!text1.length||!text2.length){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
let ans=text1*text2;
document.getElementById('P').innerHTML=ans;
document.getElementById('zero').innerHTML='×';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body align="center">
<input type="text" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="text" placeholder="enter a value"id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</body>
</html>
let text1, text2;
// returning the value inside the texbox.
document.getElementById('mul').onclick=()=>{
text1=parseInt(document.getElementById('text1').value)
text2=parseInt(document.getElementById('text2').value)
// checking if the textbox is blank or not. The reason why I checked the whether the length is greater than zero in the above logic is because this logic. whenever I did not gave any values and click the submit button it is showing 'you can multiply with decimal points', the above statement's message.
if(text1.length==0){
document.getElementById('P').innerHTML='you cant do any calculations with blank textbox';
}
// else, if it has no problem just multiply.
else{
document.getElementById('P').innerHTML=text1*text2;
document.getElementById('zero').innerHTML='×';
}
}
<html lang="en"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>calculator</title>
<link rel="stylesheet" href="calculator.css">
</head>
<body style="text-align: center;">
<input type="number" min="0" id="text1" placeholder="enter a value">
<p id="zero"></p><input type="number" min="0" placeholder="enter a value" id="text2">
<br><br><br><p id="P"></p>
<br><br><br><br><br><button id="mul">Multiply</button>
<br><br><br><br><br><button id="sub">Subtract</button>
<br><br><br><br><br><button id="div">Divide</button>
<br><br><br><br><br><button id="add">Add</button>
<script src="calculator.js"></script>
</html>
Explaining code:
First, I rewrite all input types to number, so now user can't write any symbols except numbers, and I'm removed isNaN check because of reason I said before. Also, I used only text1 and text2 variables and removed ans variable because calculating is doing right before writing calculated number in innerHTML. Plus numbers automatically parsed as integers, so I removed integer check.
Here's your app working 100%.
The reason your code wasn't working because there is no length property on a number type. length is only on arrays and strings.
Some issues with your code:
text1 and text2 shouldn't be let variables at the top of the global scope. They should be pointers to their respective DOM nodes, which .value can be used on at any time.
Instead of using Element.onclick, use Element.addEventListener('click', callback) instead.
Avoid using innerHTML. Is is best practice to use textContent or innerText (textContent is best).
You can set an input element's type to be number, which will prevent the user from ever even entering a non-number value.
When you have a ton of else if statements, it's better syntactically to use a switch case (some might argue against this, but in my opinion it's much easier to read).
I rarely see the <br> tag being used in modern web-applications. Use it sparingly, and opt for flex or grid instead to space out your items.
Don't use the == operator, instead, use the "strict equals" operator: ===
If you're checking for whether or not a condition is false, you don't have to do if (conditon === false). You can negate the condition with the ! operator: if (!condition). This will also fire if the condition returns a falsy value, such as '', 0, undefined, null, or NaN.
Most importantly, try to separate your logic into "Lego blocks". Basically, make small functions that do one thing. Debugging mega functions is not fun. We've implemented this functional logic in the example below by creating the validate function.
const textbox1 = document.querySelector('#text1');
const textbox2 = document.querySelector('#text2');
const pTag = document.querySelector('#P');
const actions = {
mul: 'mul',
sub: 'sub',
div: 'div',
add: 'add',
};
const validate = (num1, num2) => {
if (isNaN(num1) || isNaN(num2) || !Number.isInteger(num1 + num2)) return false;
return true;
};
const handleClick = ({ target }) => {
let answer;
const val1 = +textbox1.value;
const val2 = +textbox2.value;
if (!validate(val1, val2)) {
pTag.textContent = 'Invalid input! Much provide two integers.';
return;
}
switch (target.getAttribute('id')) {
case actions.add:
answer = val1 + val2;
break;
case actions.sub:
answer = val1 - val2;
break;
case actions.div:
answer = val1 / val2;
break;
case actions.mul:
answer = val1 * val2;
}
pTag.textContent = answer;
};
window.addEventListener('DOMContentLoaded', () => {
for (const action of Object.values(actions)) {
const elem = document.querySelector(`#${action}`);
elem.addEventListener('click', handleClick);
}
});
<body>
<input type="number" id="text1" placeholder="enter a value" />
<p id="zero"></p>
<input type="number" placeholder="enter a value" id="text2" />
<p id="P" style="color: red"></p>
<div style="display: flex; flex-direction: column; gap: 20px; max-width: 200px">
<button id="mul">Multiply</button>
<button id="sub">Subtract</button>
<button id="div">Divide</button>
<button id="add">Add</button>
</div>
</body>
so I am doing a function which supposed to make a block of 10 numbers, but in case if it is a string, prompt "can't be string" with window.alert.
So I am making a test with console.log to check if the value isNaN or not. It always returns true, but if I am doing the same thing in browser it is false, this is what makes me struggling. Kindly thank you for sharing your wisdom with me !
I was looking for the answer without success. Best regards.
btnCheck.addEventListener("click", divFunction);
function divFunction(){
var number = Number(document.getElementById("number").value);
console.log(isNaN(number.value)); //Why it always print true ?
if(isNaN(number.value) === "true"){window.alert("CAN'T BE STRING")}else{
document.getElementById("myDiv").innerHTML="";
var i;
for (i=0;i<10;i++){
document.getElementById("myDiv").innerHTML+=number+"</br>";
}
}
}
<input type="text" id="number" placeholder="give me number"></input>
</br>
<button id="buttonCheck">Cyc</button>
</br>
<div id="myDiv"></div>
You need to remove the .value part. Do this instead:
isNaN(number)
I'm trying to use str.replace in order to remove any non-numerical characters from a number imput field when someone uses copy-pastes something in it. However the function always seems to remove all characters instead of just removing the non-numerical ones.
Surprisingly the function is able to detect when my string is purely numerical and won't change it in those cases, but adding a single other character will cause the whole string to be ditched instead of just removing the wrong characters.
I tried to change the regexp of the function to /\D/, but it didn't amount much.
Here's a minimal reproducible example, which must be run on Firefox.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script src="../lib/jquery-3.3.1.js"></script>
<input type="number" id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function()
{
$(document).ready(function()
{
input.value = input.value.replace(/[^0-9]/g, "");
});
}
</script>
</body>
</html>
I expect an output such as "34a01 2" to be "34012", but the actual output is "" (nothing). Is there something wrong in my regexp ?
let input = document.getElementById("inp");
input.onblur = function() {
$(document).ready(function() {
input.value = input.value.replace(/[^0-9]/g, "");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="inp"></input>
This looks to be a Firefox issue (or bug). Whenever a numeric input has non-numeric characters anywhere, the .value of the field will be the empty string:
setInterval(() => {
console.log(input.value);
}, 400);
<input id="input" type="number">
It's unfortunate, but you may have to simply remove the type="number" for the .value to be retrieved and replaced as desired:
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]/g, "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inp"></input>
Either that, or keep type="number" and tell the user that the value they attempted to paste is invalid, and prevent it (because you have no way of retrieving and replacing it).
(also: only call $(document).ready once, when you're adding the listeners, if at all - your current code is adding a new listener every time the field is blurred)
I've read your comments about Firefox and I've prepared a new version.
Not including the "number" type seems to work.
Using "number" type is not causing any issue in Chrome so I guess that Firefox is not behaving in the same way.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body style="margin:0px;">
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<input id="inp"></input>
<script>
let input = document.getElementById("inp");
input.onblur = function() {
input.value = input.value.replace(/[^0-9]+/g, "");
}
</script>
</body>
</html>
I am trying to make a number guessing game I have the basic part of it down but I am trying to manipulate it so that it initially stores a random number and from there the player keeps guessing till they get it right. If I should continue with the switch statement let me know or should i go back to the if/else statement.
<!DOCTYPE html>
<html>
<style>
</style>
<body>
<h1 id="prompt">Can you guess the number I am thinking of?</h1>
<h2 id="prompt2"></h2>
<input id="guess" type="text" value=""> <!--Box for the input-->
<input type="button" value="guess" onclick="numberGuess();"><!--Button
that exacutes the code-->
</body>
<script>
var randomNumber =Math.floor((Math.random()*10)+1)
function numberGuess() {
var number= randomNumber;
var yourGuess=document.getElementById('guess');
switch (guesspart) {
case (yourGuess==randomNumber) :
console.log('Correct');
break;
case (yourGuess!=randomNumber):
console.log('Correct');
break;
default:
console.log(number);
}};
/*if (yourGuess==randomNumber){
document.getElementById('prompt').innerHTML ='You have guessed
Correctly';
}
else (yourGuess!=randomNumber)
document.getElementById('prompt').innerHTML='Sorry the number was
'+randomNumber;
};*/
</script>
</html>
General Answer
For situations where there are two outcomes to the condition (i.e. a correct answer or an incorrect answer), you should use if/else.
In order to for the comparison to work, you must set yourGuess as document.getElementById('guess').value. Right now you're comparing the DOM input to the correct answer (number), which will always fail.
Performance Implications
Using an If/else statement may be more performant, as it does not need to evaluate the condition of yourGuess!=randomNumber. This is true because we know that if they're not equal, they must be unequal.
Heres an example,
if (yourGuess==randomNumber) {
console.log('Correct');
}
else {
console.log('Incorrect');
}
Notice that we're only evaluating the condition of yourGuess==randomNumber, and not yourGuess!=randomNumber also.
No need for that switch statement which could and should be done using a simple if/else.
You need to get the value from the element document.getElementBydId('guess').value
var randomNumber =Math.floor((Math.random()*10)+1)
function numberGuess() {
var number= randomNumber;
var yourGuess=parseInt(document.getElementById('guess').value);
if(yourGuess === randomNumber) {
console.log("Correct");
} else {
console.log("Incorrect");
}
};
<h1 id="prompt">Can you guess the number I am thinking of?</h1>
<h2 id="prompt2"></h2>
<input id="guess" type="text" value=""> <!--Box for the input-->
<input type="button" value="guess" onclick="numberGuess();"><!--Button
that exacutes the code-->
I can not find why this does not work. "document.getElementById("number").value" won't "return" in function..
My HTML code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Currency_Converter.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
</head>
<body>
<div class="container">
<h1>Currency Converter</h1>
<form id="amount">Dollar amount $<input id="number" type="number" name="number" onkeyup="getDollarAmount();" onchange="getDollarAmount();" placeholder="type dollar amount here" ></form>
</div>
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type='text/javascript' src="Currency_Converter.js"></script>
</html>
My JavaScript:
function getDollarAmount() {
var dollarAmount = document.getElementById("number").value;
return (dollarAmount);
}
console.log(getDollarAmount());
My "function getDollarAmount()" does not return the number put into the form. When I "console.log (dollarAmount)" I get my input. When I take out the "document.getElementById("number").value" and replace it with a number, (ex.: 5) the "getDollarAmount" function returns the number (5).
Obviously, the issue is with "document.getElementById("number").value" since the function works in every other way. What do I need to do to get "document.getElementById("number").value" to be returned to "getDollarAmount()"?
Try
var dollarAmount = $("#number").val();
The mistake here is that you are returning the value instead of assigning the dollarAmount variable to the input value attribute.
Apart from that the idea to return the converted currency value in the same place you type the amount you want to convert to is not a good practice and will be confusing.
You should have a place to input and a place to show the converted value. It's a better user experience and better for you.
You don't need jQuery. Here's an example:
var el = document.getElementById("number");
el.addEventListener("keyup", function() {
//You need to assign the value to a variable
var dollarAmount = getDollarAmount();
});
function getDollarAmount() {
return el.value;
}
<input id="number" type="number" name="number" placeholder="type dollar amount here" value="0" >
Hope it helps.
The problem is that console.log() is not getting called recursively while the value being returned by the onkeyup keeps changing.
function getDollarAmount() {
var dollarAmount = document.getElementById("number").value;
return (dollarAmount);
}
document.getElementById("number").onkeyup= () => {console.log(getDollarAmount())};