Displaying an invalid output in JavaScript [duplicate] - javascript

This question already has answers here:
Switch Statement, it does not work with prompt
(3 answers)
Closed 2 years ago.
I did the below code. But the final answer doesn't come. it always shows up as "invalid input". Can i know the reason for it ? :) is it something wrong with my switch statement? Thank you so much. Have a nice day and stay safe!
<html>
<head>
<script language="JavaScript" type="text/javascript">
function link()
{
var r=prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul");
if(r>4)
{
alert("invalid input");
}
else {
var n1=prompt("1st number:");
var n2=prompt("2nd number:");
a=n1+n2;
s=n1-n2;
d=n1/n2;
m=n1*n2;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input");
}
} }
</script>
</head>
<body>
<script language="JavaScript" type="text/JavaScript" >
</script>
<input type="button" value="maths" onclick=link()>
<script src="java.js"></script>
</body>
</html>

Prompt gives you a string back you should use parseInt
<html>
<head>
<script language="JavaScript" type="text/javascript">
function link()
{
var r=prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul");
r = parseInt(r);
if(r>4)
{
alert("invalid input");
}
else {
var n1=prompt("1st number:");
var n2=prompt("2nd number:");
let x = parseInt(n1)
let y = parseInt(n2)
a=x+y;
s=x-y;
d=x/y;
m=x*y;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input");
}
} }
</script>
</head>
<body>
<script language="JavaScript" type="text/JavaScript" >
</script>
<input type="button" value="maths" onclick=link()>
<script src="java.js"></script>
</body>
</html>

Convert string to integer. Try with the below code.
function link()
{
var r=parseInt(prompt("Enter the operation:"+'\n'+"1-addition 2-sub 3-div 4- mul"));
if(r>4)
{
alert("invalid input");
}
else {
var n1=parseInt(prompt("1st number:"));
var n2=parseInt(prompt("2nd number:"));
a=n1+n2;
s=n1-n2;
d=n1/n2;
m=n1*n2;
switch(r)
{
case 1:document.write("Addition answer = "+a);break;
case 2:document.write("Substraction answer = "+s);break;
case 3:document.write("Division answer = "+d);break;
case 4:document.write("Multiplication answer = "+m);break;
default:document.write("invalid Input22");
}
} }
<input type="button" value="maths" onclick=link()>

Related

Converting input to lowercase

not a coder at all, making a little project. Does anyone know how I can make my input here case insensitive? I have tried to add a line similar to
name = name.map(function(x){ return x.toLowerCase() })
but this didn't work and with no coding background I'm finding it hard to troubleshoot what is going wrong.
Thank you :)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val();
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>
To have case insensitivity you need to have both the values in same case, whereas you're just changing value of names to lowerCase but not the value of name toLowerCase.
So just change both the values to same case and than match
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
return x.toLowerCase()
})
$('#check').click(function() {
var name = $('#name').val().toLowerCase(); // notice to lowercase here
if (jQuery.inArray(name, names) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
</script>
</body>
</html>
You can convert the input to lowercase using toLowerCase() and then check if is present in array or not . i.e :
$(document).ready(function() {
var names = ["B1", "B2", "B3", "B4", "B5"];
names = names.map(function(x) {
var a= x.toLowerCase()
console.log(a);
$('#check').click(function() {
var name = $('#name').val().toLowerCase();
if (jQuery.inArray(name, a) != '-1') {
document.getElementById("para").innerHTML = "We cover this postcode";
} else {
document.getElementById("para").innerHTML = "We do not cover this postcode ";
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<input id="name" type="text">
<input id="check" type="button" value="Check">
<p id="para"></p>
Take the text in variable, then pass it with toLowerCase() function.
var str = "Hello World!";
var res = str.toLowerCase();
var strring = "Convert String to Lower";
var result = str.toLowerCase();

JavaScript RegEX Test not working

I want to check if input text (amount) is between 1-100 or not but regex test not working.
here is my JS code
<script type="text/javascript" >
console.log(document.getElementById("amount").value); // 222
var regex = /^(100)|[1-9]\d?$/;
if(regex.test(document.getElementById("amount").value))
{
alert('validated')
}
else
alert('error')
</script>
Wrap the code in DOMContentLoaded event callback
Don't use RegEx. Use comparison operators
Code:
document.addEventListener('DOMContentLoaded', function () {
// Get the value & convert it into Number
var value = parseInt(document.getElementById('amount').value, 10);
// Value between 0 & 100
if (value > 0 && value <= 100) {
alert('Valid');
} else {
alert('Error');
}
});
It would be enough to use parseInt() function or Number constructor to perform such a simple validation:
<script type="text/javascript" >
var amount = Number(document.getElementById("amount").value); // 222
alert ((amount > 0 && amount <= 100)? 'Valid' : 'Invalid');
</script>
If you really want to use regex, this should work:
/^100$|^[1-9]\d?$/
It doesn't allow eg 09, but maybe that's OK.
<html>
<head>
<script>
function validateValue()
{
var amount = document.getElementById('testId').value;
if((isNaN(amount ))){
document.getElementById("errorId").style.display= "";
}
else
{
if(amount>100){
document.getElementById("errorId").style.display= "";
}
else
{
document.getElementById("errorId").style.display= "none";
}
}
}
</script>
</head>
<body>
Enter 1 to 100:<input type="text" onkeyup="validateValue()" id="testId"/>
<span id="errorId" style="color:red;display:none"> Not a valid amount</span>
</body>
</html>

piece of html+javascript that finds if number from an input is prime then displays the result

School project. I must design a page that contains an input box, a button that sends the entered number to the function, and a paragraph that displays the result. Here's my progress as of now, problem is it just says "false" everytime. Sorry for the triviality of the question, i'm a total newb with web coding.
<!DOCTYPE html>
<html>
<head>
<script>
function isPrime($n)
{
$i=2;
if ($n==2){
return true;
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
return false;
}
$i++;
}
return true;
}
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="isPrime(n)">
</form>
<p id="derp">sdvfsdg</p>
<script>
document.getElementById("derp").innerHTML = isPrime(n);
</script>
</body>
</html>
Basically you are setting the content of the derp once and for all before pressing the button
function isPrime($n)
{
$i=2;
if ($n==2){
document.getElementById("derp").innerHTML = "True";
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
document.getElementById("derp").innerHTML = "False";
}
$i++;
}
document.getElementById("derp").innerHTML = "True";
}
And not sure you really need the $ everywhere - that's a PHP thing
You had not used input field value at all, that was your mistake
Value:
<input type="number" id="n">
<br>
<input type="submit" value="Sebd" onclick="x()">
</form>
<p id="derp">sdvfsdg</p>
<div id="try">jdfs</div>
<script>
function x() {
document.getElementById('derp').innerHTML = isPrime(Number(document.getElementById('n').value));
}
function isPrime(n) {
i = 2;
if (n == 2) {
return true;
}
sqrtN = Math.sqrt(n);
document.getElementById('try').innerHTML = n;
while (i <= sqrtN) {
document.getElementById('try').innerHTML = 'try';
if (n % i == 0) {
return false;
}
i++;
}
return true;
}
</script>
Here's the code that'll work for your case... You should execute the code on click AFTER entering the value
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="checkPrime()"> <!--use function on click-->
</form>
<p id="derp">sdvfsdg</p>
<script>
function isPrime(num)
{
var isPrime = true; //initially set to true
for(var i=2; i<num; i++){
if(num%i == 0){ //if the num gets divide by any other number except itself
isPrime = false;
}
}
return isPrime;
}
function checkPrime(){ //function that gets called on send button click
var number = document.getElementById("n").value; //get the value of input
number = parseInt(number); //since it's a string,convert it into number
document.getElementById("derp").innerHTML = isPrime(number); //check if prime and display result
}
</script>
</body>
</html>

JavaScript Quiz Not Working

I am trying to make a little quiz to study.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div id="question"></div>
<form>
<input type="text" id="answer">
<button onClick="check()">Check</button>
</form>
<script>
var spanish = new Array("Hola", "Sí", "No");
var english = new Array("Hello", "Yes", "No");
var x = Math.floor(Math.random()*3);
document.getElementById("question").innerHTML = english[x];
var attempt = document.getElementById("answer");
var correct = spanish[x];
function check(){
if(attempt == correct){
alert("Correct");
}else{
alert("Fail");
};
};
</script>
</body>
</html>
It is returning Fail no matter if I am right or not. Do you know how to fix this? I looked around but could not figure out what is wrong. Thanks.
You need to check for attempt upon clicking the button. You're currently checking it on page load (so it's always an empty string, which is causing correct == attempt to be false). Also, you need to grab the value, not the element.
So, change your function to:
function check() {
var attempt = document.getElementById("answer").value;
if (attempt == correct) {
alert("Correct");
} else {
alert("Fail");
};
};
See here: http://jsfiddle.net/ykZHa/

check text box value is according to a prefix

I have text box.
Users can enter Student Id into that.
Student id is in this format DIP0001.
First three letters should be DIP and the remaining 4 digits should be numeric and can only upto 4 characters.
So how can I check whether entered data is in this format using javascript.
Please help.....
You could build a regular expression pattern and test it against that value to see if it matches that exact pattern.
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
<label for="studentId">Student ID</label>
<input id="studentId" type="text">
<button id="btn" type="button">Validate</button>
// Embedded script so that you don't have to load an external file
<script>
var input = document.getElementById('studentId');
var btn = document.getElementById('btn');
var pattern = /DIP+\d{1,3}/g;
btn.addEventListener('click', function(){
if(pattern.test(input.value)) {
alert('It enter code here`atches!');
}else {
alert('It does not match!');
}
});
</script>
</body>
</html>
JS FILE:
// This pattern looks something like this: DIP0000
var pattern = /DIP+\d{1,3}/g;
// studentId is the ID of the input field that contains the Student ID
var studentIdInput = document.getElementById('studentId');
// Check the pattern against the provided Student ID
if(pattern.test(studentIdInput.value)) {
alert('It matches the pattern!');
}
EDIT 1: I have built the functionality in the following JSFiddle: http://jsfiddle.net/vldzamfirescu/QBNrW/
Hope it helps!
EDIT2: I have updated the JSFiddle to match any other combinations up to 4 digits; check it out: http://jsfiddle.net/vldzamfirescu/QBNrW/1/ Let me know if it solved your problem!
try this code
<html>
<head>
<script>
function validate(val) {
if (val.value != "") {
var filter = /^[DIP]|[dip]+[\d]{1,4}$/
if (filter.test(val.value)) { return (true); }
else { alert("Please enter currect Student Id"); }
val.focus();
return false;
}
}
</script>
</head>
<body>
<input id="Text1" type="text" onblur="return validate(this);" />
</body>
</html>
Use Regular Expresions.
If found a valid Student ID, the pattern will return true:
function validateStudentId(id) {
var re = /DIP[0-9]{4}/;
return re.test(id);
}
// Edited for use with a click event:
document.getElementById('button').addEventListener('click', function(){
if( validateStudentId(document.getElementById('textBox').value) ){
alert('correct');
}else{
alert('invalid ID');
}
});

Categories

Resources