not able to display JAVASCRIPT RESULT on html - javascript

I am trying to make a function in JAVASCRIPT that calculates the HCF, in the VS CODE (MY CODE EDITOR) console it's showing the correct value, but I am trying to display the result on the page and it's not appearing and in the browser's console its showing maximum call stack exceeded.
The result of the if statement appears but when the if statement is false, the result of the else statement does not appear.
Here is my code:
function HCF(a, b) {
var answer = document.getElementById('answer');
let value1 = document.getElementById('value1').value;
let value2 = document.getElementById('value2').value;
a = value1;
b = value2;
var ans = 0;
if (a % b == 0) {
return answer.innerHTML = `HCF: ${b}`;
}
var remainder = a % b;
ans += HCF(b, remainder);
answer.innerHTML = `HCF: ${ans}`;
}
<!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>Maths Problem</title>
</head>
<body>
<h1>Value 1: </h1><input type="text" id="value1">
<h1>Value 2: </h1><input type="text" id="value2"><br><br>
<button type="submit" id="submit" onclick="HCF()">Get answer</button>
<h1 id="answer">HCF:</h1>
</body>
</html>

You need to separate out the code that calculates the HCF and which gets and displays values.
function HCF(a, b) {
if (a % b == 0) {
return b;
}
var remainder = a % b;
return HCF(b, remainder);
}
function getHCF() {
const a = document.getElementById('value1').value;
const b = document.getElementById('value2').value;
const answer = HCF(a, b);
document.getElementById('answer').innerHTML = `HCF: ${answer}`;
}
<h1>Value 1: </h1><input type="text" id="value1">
<h1>Value 2: </h1><input type="text" id="value2"><br><br>
<button type="submit" id="submit" onclick="getHCF()">Get answer</button>
<h1 id="answer">HCF:</h1>
</body>

I've separated your function into two functions. One function calls the other which is recursive and which returns the answer to the first function which then displays the results to the page.
function HCF() {
var answer = document.getElementById('answer');
let value1 = document.getElementById('value1').value;
let value2 = document.getElementById('value2').value;
answer.innerHTML = HCFHelper(value1, value2);
}
function HCFHelper(a, b) {
if (a % b == 0) {
return b;
}
return HCFHelper(b, a % b);
}
<!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>Maths Problem</title>
</head>
<body>
<h1>Value 1: </h1><input type="text" id="value1">
<h1>Value 2: </h1><input type="text" id="value2"><br><br>
<button type="submit" id="submit" onclick="HCF()">Get answer</button>
<h1 id="answer">HCF:</h1>
</body>
</html>

Related

How to print out numbers in JS

I'm learning JS and I coded an "arabic to roman numbers" converter. Everything is working fine when I console log. But the next step is to display these informations in html like following :
Arabic number :
Roman number :
Here's my code so far :
<!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>Converter</title>
</head>
<body>
<p>Arabic number :</p>
<p id="numberInput"></p>
<p>Roman number :</p>
<p id="romainInput"></p>
<script src="./index.js"></script>
</body>
</html>
And the Js part :
let romanInput = document.getElementById("romanIput");
let arabicInput = document.getElementById("numberInput");
function convertToRoman(num) {
const romanToNum = {
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let roman = "";
for (let key in romanToNum) {
while (num >= romanToNum[key]) {
roman += key;
num -= romanToNum[key];
}
}
return roman;
}
console.log(convertToRoman(2));
I just need to choose a random number in the console between 1 and 10 and to display it. I tried different things with "romanInput.innerHtml = roman.value" and things like that but nothing working so far. Any ideas ?
Thanks in advance...
if you want to generate random number and pass it to your function you can write a function like this:
function getRandomNumberBetween(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
var rndNum = getRandomNumberBetween(1,10);
console.log(convertToRoman(rndNum));
You had miss spelled innerHTML as innerHtml. That's why it won't work.
let romanInput = document.getElementById("romanIput");
let arabicInput = document.getElementById("numberInput");
function convertToRoman(num) {
const romanToNum = {
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let roman = "";
for (let key in romanToNum) {
while (num >= romanToNum[key]) {
roman += key;
num -= romanToNum[key];
}
}
return roman;
}
arabicInput.innerHTML = convertToRoman(2)
<!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>Converter</title>
</head>
<body>
<p>Arabic number :</p>
<p id="numberInput"></p>
<p>Roman number :</p>
<p id="romainInput"></p>
</body>
</html>
You are nearly there. Just add an eventlistener to your input field and actual make it a html input field.
After this you can listen to events and read the value which is in the input.
I used the keyup event to update the value immediately.
let romanOutput = document.getElementById("romanOutput");
let arabicInput = document.getElementById("numberInput");
arabicInput.addEventListener("keyup", e => convertToRoman(Number(e.target.value)))
function convertToRoman(num) {
const romanToNum = {
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let roman = "";
for (let key in romanToNum) {
while (num >= romanToNum[key]) {
roman += key;
num -= romanToNum[key];
}
}
romanOutput.innerHTML = roman;
}
<!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>Converter</title>
</head>
<body>
<p>Arabic number :</p>
<input id="numberInput" />
<p>Roman number :</p>
<p id="romanOutput"></p>
</body>
</html>

Updating array in Todo list in javascript

I have been trying every method to update an array in my todo list using Javascript. But I am stuck in update function. I have tried every method possible but nothing seems to work.
Can anyone please help?
I have been stuck in the Update function for days now.I have declared the ind as a global variable. Assigned value in Edit functiion and called it back in update function. But still not working. Not sure, what the exact way is to update my array todo list in JS.
Below is my 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>Arrays</title>
</head>
<script>
var arr = ["A", "B", "C"];
var ind;
function display() {
var dom = "<ul>";
for (i = 0; i < arr.length; i++) {
dom += "<li>" + arr[i] + "<input type='button' value='Edit' onclick='Edit(" + i + ")'></li>"
}
dom += "</ul>";
document.getElementById("do").innerHTML = dom;
}
function Selection(s) {
var ip = document.getElementById("input").value.trim();
var s;
switch (s) {
case 'op1':
arr.push(ip);
display();
break;
case 'op2':
arr.pop();
display();
break;
case 'op3':
arr.shift();
display();
break;
case 'op4':
arr.unshift(ip);
display();
break;
}
}
}
function Edit(ind) {
//alert(ind);
document.getElementById("editList").style.display = "Block";
document.getElementById("val").value = arr[ind];
ind = ind;
}
function update() {
Edit();
var updte = document.getElementById("val").value;
arr[ind] = updte;
}
</script>
<body onload="display()">
<h1>To Do List</h1>
<div id="do"></div>
Enter data : <input type="text" id="input"><br><br>
<input type="button" value="op1" onclick="Selection
('op1')">
<input type="button" value="op2" onclick="Selection('op2')">
<input type="button" value="op3" onclick="Selection('op3')">
<input type="button" value="op4" onclick="Selection('op4')">
<span id="select"></span>
<div id="editList" style="display:none">
<h2> Edit ToDo List</h2><br> To be updated: <input type="text" id="val"><br>
<input type="button" value="Update" onclick="update()">
</div>
</body>
</html>
Check at lines 46 and remove } symbol above edit function. You have 1 unnecessary symbol at this line
try to use let i in for (i = 0; i < arr.length; i++)
like this:
for (let i = 0; i < arr.length; i++) {
You need to have a way to know the actual ind when you click on the update button.
I have done it using dataset. Have a look at your edit and update functions below.
<!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>Arrays</title>
<script>
var arr = ["A", "B", "C"];
var ind;
function display() {
var dom = "<ul>";
for (i = 0; i < arr.length; i++) {
dom += "<li>" + arr[i] + "<input type='button' value='Edit' onclick='Edit(" + i + ")'></li>"
}
dom += "</ul>";
document.getElementById("do").innerHTML = dom;
}
function Selection(s) {
var ip = document.getElementById("input").value.trim();
var s;
switch (s) {
case 'op1':
arr.push(ip);
display();
break;
case 'op2':
arr.pop();
display();
break;
case 'op3':
arr.shift();
display();
break;
case 'op4':
arr.unshift(ip);
display();
break;
}
}
function Edit(ind) {
//alert(ind);
document.getElementById("editList").style.display = "Block";
document.getElementById("val").value = arr[ind];
document.getElementById("val").dataset.ind = ind
ind = ind;
}
function update() {
//Edit();
var updte = document.getElementById("val").value;
ind = document.getElementById("val").dataset.ind
arr[ind] = updte;
display()
}
</script>
</head>
<body onload="display()">
<h1>To Do List</h1>
<div id="do"></div>
Enter data : <input type="text" id="input"><br><br>
<input type="button" value="op1" onclick="Selection
('op1')">
<input type="button" value="op2" onclick="Selection('op2')">
<input type="button" value="op3" onclick="Selection('op3')">
<input type="button" value="op4" onclick="Selection('op4')">
<span id="select"></span>
<div id="editList" style="display:none">
<h2> Edit ToDo List</h2><br> To be updated: <input type="text" id="val"><br>
<input type="button" value="Update" onclick="update()">
</div>
</body>
</html>

How to take user input as argument of function in JavaScript in order to implement Insertion Sort Algorithm?

Below is the function for insertion sort. I want that user should give the input from html form as an array elements instead of hard coding the elements of array. I have tried several techniques but in vain.
function insertionSort (inputArr) {
let length = inputArr.length;
for (let i = 1; i < length; i++) {
let key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
inputArr[j + 1] = inputArr[j];
j = j - 1;
}
inputArr[j + 1] = key;
}
return inputArr;
};
let inputArr = [2,4,5,36,2,6,26,8,3,7]; // I want here user input which comes from html form instead of hard-coding elements of array like this
insertionSort(inputArr);
console.log(inputArr);
// Event listner
function getData() {
let userData = document.getElementById('data').value;
return userData;
}
<!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>Insertion Sort In JavaScript</title>
</head>
<body>
<h1>Insertion Sort in JavaScript</h1>
<form action="#">
<label for="data">Write Random Numbers</label>
<input type="text" name="data" id="data">
<button onclick="getData()">Submit</button>
</form>
<div id="printData"></div>
<script src="insertionsort.js"></script>

Javascript var length off when it ends in 00

I am formatting the phone field. I get the value of the element and check to see if it 3 characters. The problem comes when the value ends with two zeros. The length of the var is off if it ends in two zeros.
Example:
120 value comes in at 3
1200 value also comes in at 3
//phone format
function updatephone(x) {
var phlen = document.getElementById("fphone").value;
if (phlen.length < 12) {
if (phlen.length == 3) {
document.getElementById('fphone').value=document.getElementById('fphone').value + -x;
}
else if (phlen.length == 7) {
document.getElementById('fphone').value=document.getElementById('fphone').value + -x;
}
else {
document.getElementById('fphone').value=document.getElementById('fphone').value + x;
}
}
}
Here its code its working prefect
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id='phone' oninput="test()" type="number" />
<input id='result' />
<script>
function test()
{
var v=document.getElementById("phone").value;
if(v.length<12)
{
if(v.length==3)
{
document.getElementById("result").value="3";
}else
{
document.getElementById("result").value="";
}
}else if(String(v).Lenght>=12)
{
alert("Wrong")
}
}
</script>
</body>
</html>

Finding Factorial of a number through prompt from the user

I have been struggling with the this output from which hangs my browser. When I run the following code it runs fine.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = 5;
for(var i=1;i< 5;i++){
input = i*input;
}
document.write(input);
</script>
</body>
</html>
But this hangs the browser and I have to stop it finally. I cant't find any bug or error in this code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = prompt("Enter the number to get factorial of: ");
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
</script>
</body>
</html>
input = i*input; increases input so i < input is always false. Try smth like
var input = parseInt(prompt("Enter the number to get factorial of: "));
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
var x=parseInt(num);
if(x>0)
x=x* fact(x-1);
alert(x);
}</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="fact(txt1.value)">
</form>
</body>
var y = prompt("type number ");
var x = input;
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
run(x);

Categories