Can't get result to display in page below input - javascript

I can't get the result to display on the html page, which is why i have it as an alert
<h1>Factorial Problem</h1>
<form name="frm1">
Enter any number :<input type="text" name="fact1"><br><br>
<input type="submit" value="Calculate" onclick="fact(frm1.fact1.value)">
here is the JavaScript
function fact(n){
var m=1;
while(n){
m=m*n;
n--;
}
alert("Factorial of given number :"+" "+ m);
}

You need to add an identifier in the DOM to inject the value with JS.
As an example, I toke you'r code and added a div with the id with the value 'result'.
Then with JS, we inject the value in the DOM on the click event of you'r button.
<h1>Factorial Problem</h1>
<form name="frm1">
Enter any number :<input type="text" name="fact1"><br><br>
<div id="result"></div>
<input type="button" value="Calculate" onclick="fact(frm1.fact1.value)">
function fact(n){
var m=1;
while(n){
m=m*n;
n--;
}
var el = document.getElementById('result');
el.innerHTML = "Factorial of given number :"+" "+ m;
// alert("Factorial of given number :"+" "+ m);
}

<body>
<h1>Factorial Problem</h1>
Enter any number :<input type="text" id="fact1"><br><br>
<input type="submit" value="Calculate" onclick="fact()">
<p id="result"></p>
</body>
function fact(){
var m=1;
var n=document.getElementById("fact1").value;
while(n){
m=m*n;
n--;
}
//alert("Factorial of given number :"+" "+ m);
document.getElementById("result").innerHTML=m;
}

Related

How to print the values in the same input text field using JS

I have created 5 input text boxes using HTML and made a button while clicking the button the values will print the result input text box. The first 4 fields are my inputs and the last text field is my output. unable to debug the issue. kindly find the code and help to find the issue.
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(h+w+g+t);
document.getElementById('result').innerHTML=total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2"id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<!--
<p
id="result">
</p>
-->
<button id="btn" onClick="JS()">Calculate</button>
There are two keys to resolving your issue:
Coerce your inputs to numbers, which I'm doing by adding a + in front of the value assignments. If you don't do this, your values may be treated like strings and concatenated rather than added like numbers.
Set the value of the input element, not the innerHTML. If you'd rather use a <p> element, which it appears you commented out in your sample code (and which I restored for completeness of my answer), consider using innerText.
See example here:
function JS() {
var h = +document.getElementById('h').value;
var w = +document.getElementById('w').value;
var g = +document.getElementById('g').value;
var t = +document.getElementById('t').value;
let p_result = document.getElementById('p_result');
var total = (h + w + g + t);
document.getElementById('result').value = total;
p_result.innerText = total;
}
<h2> Calculator</h2>
<input type="text" placeholder="value1" id="h">
<input type="text" placeholder="value2" id="w">
<input type="text" placeholder="value3" id="g">
<input type="text" placeholder="value4" id="t">
<input type="text" placeholder="result" id="result">
<br>
<p id="p_result" style="color:red;"></p>
<br>
<button id="btn" onClick="JS()">Calculate</button>
function JS(){
var h=document.getElementById('h').value;
var w=document.getElementById('w').value;
var g=document.getElementById('g').value;
var t=document.getElementById('t').value;
var total =(Number(h)+Number(w)+Number(g)+Number(t));
document.getElementById('result').value =total;
}
.value instead of .innerHTML
also, you should convert inputs values to number cause instead of making the sum will be as consider them string( for example if you type 1 , 2 , 3 , 4 without converting to number will be 1234 if you convert to number will be 10

Proper Use of Nan

How would I implement NaN and have Inavlid input display in a element
To do this I have to use isNaN to verify that numerical values are input.
I just want it to display "Invalid input" whenever a non numeric value is put in either of the two first text boxes.
http://jsfiddle.net/hq3m1uns/1/ this is my fiddle link
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question2</title>
<style>
</style>
<script type="text/javascript">
window.onload = function(){
};
function add_number(){
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value",result);
}
</script>
</head>
<body>
<div>
<h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1">
<br> Enter Second Number : <br>
<input type="text" id="tb2" name="TextBox2">
<br> Result : <br>
<input style="width: 50%" type="text" id="tb3" name="TextBox3" >
<br>
<input onclick="add_number()" type="button" id="b1" value="GO" />
</body>
</html>
Just add a paragraph tag in your HTML file with id "msg" and do the following changes in your javascript code.
function add_number() {
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
if (isNaN(first_number) || isNaN(second_number)) {
document.getElementById('msg').innerHTML = "Invalid Input";
} else {
document.getElementById('msg').innerHTML = "";
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value", result);
}
}
<p id="msg"></p>
One way is to use a keyup event listener on the input field to validate the numeric value and update the textContent of the paragraph element based on its validity.
Another solution is to use a input type="number" for the input and use HTML5's checkValidity/reportValidity on it, but I'll leave that for you to research and learn about on your own.
function validate(inputId, helpId) {
var value = document.getElementById(inputId).value;
var help = document.getElementById(helpId);
if (isNaN(value))
help.textContent = "invalid input"
else
help.textContent = ""
}
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1" onkeyup="validate('tb1', 'help1')">
<p id="help1"></p>

How to Detect Change in a Text Input Box in jQuery

I have two text input text box and I want to do the total of whatever no entered by the user. Below is my code:
$(document).ready(function(){
var total = 0;
$(".test").on("input", function(){
// Print entered value in a div box
total += parseInt($(this).val());
$("#result").text( total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
When I input 10 first then it takes 11, then if I enter 100 then it takes 111, I am no getting why this happening. Where I am making an error, guide me?
On your code when you enter the first digit it's been calculated to the total because of your code total += parseInt($(this).val()). for example, if your press first digit as 1 then at that time total is updating as total = total + 1 which equals 1, on the second keypress, for example, take 0, then your input value becomes 10. it is calculating to the current total value as total = total + 10. that's why you are getting 11 as answer
Try like this.
$(document).ready(function(){
$(".test").on("input", function(){
let total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>
The reason it didn't showed you the result you want to, is because the calculation is wrong. You now add the number to the total, every time one input field changes. So if you type 123, it takes 0 + 1 , then 1 + 12, then 13 + 123 so you'll have 136 as result.
I wrote a possible solution for your question. The code is in the fiddle below.
You could add a function where you calculate the total of all input fields (may be more than 2, it's generic).
function calculateTotal(){
var total = 0;
$(".test").each(function( index ) {
var value = $(this).val();
if(value == ""){
return;
}
total += parseInt(value);
});
$("#result").text(total);
}
And on the change of your input fields, you just execute that function.
$(document).ready(function(){
$(".test").on("input", function(){
calculateTotal();
});
});
Your example is in this fiddle: https://jsfiddle.net/xL6hgder/2/
You just update total with that input value that you're trying to change.
For getting the total for both input values you have to take both values and add it with the total.
Try below code-
$(document).ready(function() {
$(".test").on("change", function() {
var total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
// Print entered value in a div box
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
$(document).ready(function () {
$(".test").on('input', function () {
var total = parseInt($("#result").text());
total = parseInt($("#myInput").val()) + parseInt($("#myInput1").val());
$("#result").text(total);
});
});
<p><input type="text" class="test" placeholder="Type something..." id="myInput" /></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1" /></p>
<div id="result"></div>
Use the change event instead of the input event. It will only fire when the value is "commited", instead of every keystroke. See mdn for details.

HTML form submits values and stores all of them in a new array(javascript)

I am trying to make a form with one text input and a submit button. What I want the script to do is take the text after I click submit and store it as a value. After that, if I type something else (without refreshing the page) and click submit store the input as another value. This process can be done one hunded times so I will have 100 different values. What I also want to do with this values is put them in a new array.So:
var AllValues = [""+Val1+"",""+Val2+"",""+Val3"",..,""+Val99+"",""+Val100""];.
The code I have managed to write untill now is this but it won't actually help you:
<!DOCTYPE html>
<html>
<body>
<form id="form1">
Type the words here: <input type="text" name="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
<script>
function myFunction() {
}
function myFunction2() {
var AllValues = [""+Val1+"",""+Val2+"",""+Val3"",..,""+Val99+"",""+Val100""];
document.getElementById("demo").innerHTML = AllValues;
}
</script>
</body>
</html>
I am asking this question after trying a lot of things which didn't worked and I know that the script will work only if I use HTML local storage but I don't have the knowledge to do it even if I did a lot of research on this topic. I dont want to only store the values but I want to get them inside a new Array. I am making the question a bit more general as always in order to help as many as possible. Could you please help me? Thanks in advance.
You had several issues, the main is that you have to provide the "id" attribute for the input text named "fname".
Next you have to store the AllValues array in context visible by two declared functions (in this case, the global context).
<!DOCTYPE html>
<html>
<body>
<form id="form1">
Type the words here: <input type="text" name="fname" id="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
<script>
var AllValues = [];
function myFunction() {
var fname = document.getElementById("fname").value;
AllValues.push(fname);
}
function myFunction2() {
document.getElementById("demo").innerHTML = AllValues;
}
</script>
</body>
</html>
Try also the immediate function to avoid storing variables in global context. The code that I paste is not very clean of course, but working :)
For a very basic way of doing this, try the following:
HTML:
<form id="form1">Type the words here:
<input type="text" name="fname">
<br>
<input type="button" value="Submit" class="submit">
</form>
<input type="button" class="show-button" value="Print all inserted words at array">
<p id="demo"></p>
JS:
var values = new Array();
$(".submit").on("click", function () {
values.push($('input[name="fname"]').val());
});
$(".show-button").on("click", function () {
$("#demo").html(values.join("<br>"));
});
Fiddle here: http://jsfiddle.net/5z4g04js/2/
My answer:
<form id="form1">
Type the words here: <input id="words" type="text" name="fname"><br>
<input type="button" id="submitWords" value="Submit">
</form>
<input type="button" id="printWords" value="Print all inserted words at array">
<p id="demo"></p>
<script>
var arrWords = [];
var btnSubmit = document.getElementById('submitWords');
var btnPrint = document.getElementById('printWords');
var demo = document.getElementById('demo');
btnSubmit.onclick = function() {
var words = document.getElementById('words').value;
arrWords = words.split(' ');
console.log(arrWords);
}
btnPrint.onclick = function() {
for(var i = 0; i < arrWords.length; i++) {
demo.innerHTML += arrWords[i]+"<br>";
}
}
</script>
</body>
</html>
You could use jquery to do that:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
alert(temp_val);
all_values.push(temp_val);
}
function myFunction2() {
alert(all_values);
}
<form id="form1">
Type the words here: <input type="text" name="fname" id="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
working demo
p.s. edited jquery answer with more changes. working demo
Using this getAllValues(name) function, you can return the values of any element with the name of 'name'.
function getAllValues(name) {
var nameMatches=document.getElementsByName(name);
var AllValues=[];
for (var i=0; i<nameMatches.length; i++) {
AllValues.push(nameMatches[i].name);
AllValues.push(nameMatches[i].value);
}
return AllValues;
}
To call this you would use getAllValues('fname').

How to show the text from a form with button?

I am studying web design for first year in university. We have just started and I am trying to do different things with my basic knowledge of html. My question is how can it show the text entered in a form after clicking a button? I tried something but it's not working.
This is my wrong code:
<body>
<script>
function name(name1)
{ alert ("Your name is" + name1)
}
</script>
Enter a name:
<form> <input type="text" name="name1"/></form> </br>
<button onclick="name(name1)">Click!</button>
</body>
You can to use querySelector, to get the element based using attribute selector.
<script>
function yourMethod(name1) {
var inputName = document.querySelector('input[name=' + name1 + ']').value;
console.log("Your name is: " + inputName)
}
</script>
Enter a name:
<input type="text" name="name1" />
<button onclick="yourMethod('name1')">Click!</button>
Try this
<body>
<script>
function name1(name)
{
alert("Your name is " + name);
}
</script>
Enter a name:
<form> <input type="text" name="name" id="name"/></form> </br>
<button onclick="name1(document.getElementById('name').value)">Click!</button>
</body>
try this
<body>
<script>
function name()
{
var value = document.getElementById('name1').value;
alert("Your name is" + value);
}
</script>
Enter a name:
<form>
<input type="text" id="name1" name="name1" />
</form>
</br>
<button onclick="name();">Click!</button>
</body>
make onclick="name()"
then function name(){ alert( document.querySelector("input[name='name1']").value ) }
what it does is when the button gets clicked, the function name is called. This will alert the text by finding the element with the querySelector. The query selector returns an element, if found. You can access every elements attribute with element.attributeName.
In this case you want to use querySelecor because querySelectorAll will return a nodelist. Where querySelector will return only an element

Categories

Resources