Prime Printer using js? - javascript

Hello we were given a task where a user inputs any value up to 200 only and if it's a prime, it should print prime and if not, not prime. I already changed the code precisely. However, it's not working. Why is it so?
<!DOCTYPE html>
<html>
<body>
<script>
function doAction(){
//gets the value from the text field with id input1 and stores it in variable num1
var num1 = document.getElementById("input1").value;
//HINT: loop through some finite number and check whether they are prime
//You can create a function out of the CheckPrime exercise and use that to check if a number is
Prime
//for loop the numbers until you satisfy the num1
function primeprinter(num1) {
for(var i = 2; i < num1; i++)
if(num1 % i === 0) return false;
return num1 > 1;
if (primeprinter === true){
<p> Prime </p>
}
else{
<p> Not Prime </p>
}
}
//Challenges:
//validate if the input are numbers. Hint: Check out isNaN() function
//Validate the input to only be less than equal 200
}
</script>
<h2>Prime Numbers Printer</h2>
Prints the first N prime numbers. Only try up to 200.
<br/>
<br/>
Input1: <input type="text" id="input1"/>
<button type="button" onclick="doAction()">
Print Prime</button>
<br/>
<br/>
Result:
<p id="output"></p>
</body>
</html>
I am a beginner at javascript. Please help me ;-;

You can't inline HTML in JavaScript, i.e. if (primeprinter === true){ <p> Prime </p> } else { <p> Not Prime </p> } doesn't work. You could manipulate the DOM by hand.
function primeprinter(num1) {
for (let i = 2; i < num1; i++)
if (num1 % i === 0) return false;
return num1 > 1;
}
function doAction() {
const num1 = document.getElementById("input1").value;
document.getElementById("output").innerHTML = primeprinter(num1) ? "Prime" : "Not Prime";
}
<h2>Prime Numbers Printer</h2>
<span>Prints the first N prime numbers. Only try up to 200.</span>
<br />
<br />
<label for="input1">Input1: </label><input type="text" id="input1" />
<button type="button" onclick="doAction()">Print Prime</button>
<br />
<br />
<span>Result:</span>
<p id="output"></p>

Related

How to add an if statement to check multiple variables in a function (Javascript)

This block of code in my HTML doc serves as a function to perform a calculation. It prompts the user to enter the number of rooms and total sq. ft., then multiplies the sq ft by 5 to get the estimate. I am trying to figure out how to add an if-statement to serve as an error message if a user inputs a negative number. Below is the function copied from the code. Would I add it directly in the function, before or after it? What I basically want to say is,
if (var a && b <= 0) {
print "Invalid entry. Please reload the page and enter a positive number." }
How would I go about doing this in JavaScript? Also, is there a better way to ask the user than using < p> < /p>?
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> <br>
<input type="text" name="roomSize" id="roomSize"><br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>
<script>
function submit1(){
var a = document.getElementById("numRooms").value;
var b = document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
document.getElementById("result").innerHTML="Your estimate is : $" + c;
}
</script>
You could check the values in advance and exit early, if an error occurs.
function submit1() {
var a = +document.getElementById("numRooms").value; // get a number with +
var b = +document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
if (isNaN(a) || a <= 0 || isNaN(b) || b <= 0) { // check if number or smaller/eq than zero
document.getElementById("result").innerHTML = '<span style="color: #b00;">Please insert only positive numbers.</span>';
return;
}
document.getElementById("result").innerHTML = 'Your estimate is : $ ' + c;
}
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> Rooms<br>
<input type="text" name="roomSize" id="roomSize"> Size [sq ft]<br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>

Trying a simple compare number script for study assignment [duplicate]

This question already has answers here:
How to get a number value from an input field?
(4 answers)
Closed 1 year ago.
I've been losing my mind now for a couple of hours as I can't find out what I'm doing wrong here. Trying to see if the input is equal to 3, if so then show a window saying "The number is equal to 3".
Here's the HTML and Javascript:
<input type="number" name="number" id="number">
<button id="btn" onclick="checkNumber()">Button</button>
<div>
<span id="label"></span>
</div>
<script>
var number = document.getElementById("number").value;
function checkNumber() {
if (number === 3) {
window.alert("The number is equal to 3");
}
}
</script>
The number variable should typecasted, i.e converted to number type from string type
function checkNumber() {
var number = document.getElementById("number").value;
var value = Number(number);
if (value === 3) {
alert("The number is equal to 3");
} else {
alert("The number is not equal to 3");
}
}
<html>
<body>
<input id="number" name="number" type="number" />
<button id="btn" type="button" onclick="checkNumber()">Check</button>
</body>
</html>
Input value are strings, you can change them to number by adding "+" sign.
var number = document.getElementById("number");
function myFunc() {
if (+number.value === 3) {
window.alert("The number is equal to 3");
}
}
<input type="number" name="number" id="number">
<button id="btn" onclick="myFunc()">Button</button>
<div>
<span id="label"></span>
</div>
<script>
</script>
You are using === which checks both for type and value. the input received from the user is a string while 3 is a Number.
To solve that, you must first convert the input value to Number and then compare.
Also, i would add the reference for the element outside of the function and check for the current value each time the function gets called.
var element = document.getElementById("number");
function checkNumber() {
const numberAsString = element.value;
const number = Number(numberAsString);
if (number === 3) {
window.alert("The number is equal to 3");
}
}
<input type="number" name="number" id="number">
<button id="btn" onclick="checkNumber()">Button</button>
<div>
<span id="label"></span>
</div>

finding highest number in Javascript from user input

I have tried two different Javascript code to find the largest number from three user inputs. I am not getting the highest number from none of the codes. Please help!
HTML Code:
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<input type="button" id="high" value="high" onclick="high()">
<input type="text" id="avg">
<p id="result"></p>
JavaScript Code(Try 1):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
var avg = Math.max(Number(num1),Number(num2),Number(num3))
document.getElementById("result").innerHTML=avg;
JavaScript Code(Try 2):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
if(Number(num1)>Number(num2) && Number(num1)>Number(num3))
{
document.getElementsByName("avg")[0].value = num1;
}
if(Number(num2)>Number(num1) && Number(num2)>Number(num3))
{
document.getElementsByName("avg")[0].value = num2;
}
if(Number(num3)>Number(num2) && Number(num3)>Number(num1))
{
document.getElementsByName("avg")[0].value = num3;
}
you are making things complex try this code .
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<button onclick="high()">Submit</button>
<p id="result"></p>
<script>
function high(){
var arr = document.querySelectorAll("input");
var emptyarray = [];
arr.forEach((elem) => {
emptyarray.push(elem.value);
})
var max = Math.max.apply(null, emptyarray);
document.getElementById("result").innerHTML=max;
}
</script>
you will get the heighest number result , you can restrict the input field to just enter the number so that no one can add string instead of number and your code work fine .

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Questions about javascript variable, need help~

I put 5、4 into the blanks 1st Number、2nd Number, and clicked Multiply in the output. I am looking forward to get 20, but I got zero, why?
Here's the code (also on JSBin):
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
function multiplyBy() {
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
If you are using button & form you need to specify the type of button that is submit,button or reset. The default is submit which will submit the form.
Secondly there is a typo in
<button onClick=d ivideBy()>Divide</button>
instead it will be onclick = "devideBy()"
You need to use these two variable inside the function.Reason being when js is parsing at beginning it is setting the value to 0 as those inputs are empty & inside the function you are getting 0.
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
HTML
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<!--button type button -->
<button type = "button" onClick="divideBy()">Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
JS
function multiplyBy() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 * num2;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var c = num1 / num2;
document.getElementById("result").innerHTML = c;
};
Working jsfiddle
Your first two lines run immediately when the page loads, not later when you click one of the buttons. So you get the values of the inputs as of when the page loads, which is "". * implicitly converts its operands to numbers, so "" becomes 0, and 0 * 0 is 0.
You want to get the .value from the input elements inside your click handlers, so you get the current value:
// Here we get the elements, but not their values
var num1input = document.getElementById("firstNumber");
var num2input = document.getElementById("secondNumber");
function multiplyBy() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
}
var divideBy = function() {
// Get the values as they are *now*
var c = num1input.value * num2input.value;
document.getElementById("result").innerHTML = c;
};
body {
margin: 30px;
}
<form>
1st Number :
<input type="text" id="firstNumber" />
<br>2nd Number:
<input type="text" id="secondNumber" />
<br>
<input type="button" onClick="multiplyBy()" value="Multiply" />
<button onClick=d ivideBy()>Divide</button>
</form>
<p>The Result is :
<br>
</p>
<p id="result"></p>
Side note: The value of an input is always a string. It happens that / and * will both implicitly coerce their operands to numbers, but if you did the same thing with + you'd get concatenation (one string appended to the end of the other), not addition. You want to convert your values to numbers. This answer discusses the various ways you can convert numeric strings to numbers in JavaScript.
Side note 2: As user2181397 pointed out, while the above will make your Multiply button work, there are two additional issues with your Divide button:
The default type of a button element is "submit", which will submit the form instead of just calling the click handler. Give type="button" (like you did on the input).
onClick=d ivideBy() should be onclick="divideBy()"

Categories

Resources