Disappearing HTML - Function - javascript

I am trying to make a small calculator-thingy for my website. I want to be able to write a number in a text-input, then get the double of that number back. I tried this way at first:
<form name="form">
<input type="text"/>
</form>
<script type="text/javascript">
function calc() {
var x = document.forms[0].elements[0].value;
document.write(x*2);
}
</script>
<input type="button" onClick="calc()" value="Calculate here"/>
This is working fine, but when calling the function ( calc() ) with the button, all HTML is removed. The only thing appearing is the double of the number (variable x) you wrote. I have read that the "function" make all other HTML disappear.
Is it possible to make the page stay the same, but at the same time showing the calculated number (x*2)? Can I reach the variable x without using a function?
Is it possible to "control" where and how the calculated number (x*2) is going to appear, within the JavaScript or within the HTML?
I am new to this coding art, was hoping to find a relatively easy way to solve this.
Thanks!

The best way is probably to add a div outside the form which is intended to reflect the calculated value. Then you can update calc to find this div and replace its contents with the calculated value.
<script>
function calc() {
var x = document.forms[0].elements[0].value;
var result = x * 2;
document.getElementById("result").innerHTML = result;
}
</script>
<form name="form">
<input type="text"/>
</form>
<input type="button" onclick="calc()" value="Calculate here"/>
<div id="result"></div>

Adding to your original code and the accepted answer.
Make sure that the value you retrieve is an integer(or a float).This way you will prevent the user from getting weird results.
You can do it like this:
<script>
function calc() {
var x = parseFloat(document.forms[0].elements[0].value);// or parseInt(document.forms[0].elements[0].value)
var result = x * 2;
document.getElementById("result").innerHTML = result;
}
</script>
<form name="form">
<input type="text"/>
</form>
<input type="button" onclick="calc()" value="Calculate here"/>
<div id="result"></div>

Related

Cant Get Answer Back In answer Box NAN is being shown

it does not returns prpoer answer it returnes NAN in Answer
<html>
<head>
<script type="text/javascript">
function pro(n,p)
{
var number=parseInt(n);
var powe=parseInt(p);
for(var i=1;i<powe;i++)
{
number*=number;
}
document.getElementById("answer").value=number;
}
</script>
</head>
<body>
<form name="F" >
Enter Number <input type="text" name="num" id="num"/>
Enter Power <select name="powe" id="powe">
<option value="2" >square</option>
<option value="3" >cube</option>
</select>
Answer<input type="text" name="Answer" id="answer" />
<input type="button" onClick="pro(num,powe)" value="Calculate" />
</form>
</body>
</html>
The issue is this: onClick="pro(num,powe)". Instead of the values for num and powe being gotten from the input elements and passed into the pro function, the actual element references (which are not numbers) are being passed.
To solve this problem, you'll need to get the values of the elements. But, before you just make a quick edit to your code, don't use inline HTML event attributes (onclick) in the first place. Instead, separate your JavaScript from your HTML and set up event handlers using modern standards with .addEventListener() as shown below.
Also (FYI):
Since you aren't actually submitting form data anywhere, you don't
need a <form> element.
It's not necessary to use parseInt with p.value because that
value is coming from your select and you've already set those at
whole numbers.
Don't bother with self-terminating tags (<input />) as you
gain nothing from using them.
If you are expecting only numeric input, it's better to use input
type=number which restricts the user input to numbers. Making this change also saves you from worrying about parseInt on the input number being misinterpreted as other bases than 10.
Since you don't want the user to be able to change the result of the
operation, it's better to display it in a non-editable element, like
a span.
It's a good idea to move your <script> element to just before the
closing body tag because, by the time the parser reaches that
point, all your HTML elements will have been parsed into memory.
<html>
<head>
</head>
<body>
<div>
Enter Number <input type="number" name="num" id="num">
</div>
<div>
Enter Power
<select name="powe" id="powe">
<option value="2">square</option>
<option value="3">cube</option>
</select>
</div>
<div>
Answer <span id="answer"></span>
</div>
<div>
<input type="button" value="Calculate">
</div>
<script>
// Get references to the inputs, the answer container and the button
let inputNum = document.getElementById("num");
let power = document.getElementById("powe");
let answer = document.getElementById("answer");
let btn = document.querySelector("input[type='button']");
// Set up the click event handler for the button
btn.addEventListener("click", function(){
// Now you need to get the input values and pass them
// to the function that will act with them
pro(inputNum.value, power.value);
});
function pro(n,p) {
var number = parseInt(n);
for(var i = 1; i < p; i++) {
number *= number;
}
answer.textContent = number;
}
</script>
</body>
</html>
Try
document.getElementById("answer").innerHTML = number

Ask for a html var and pass to JS

I have created a working Binary to Decimal Calculator but would like a HTML input.
<html>
<input placeholder="00000000" name="htmlinput"></input>
<input id="clickMe" type="button" value="Go" onclick="runbintodec();"></input>
</html>
<script>
function runbintodec()
{
var bin = document.getElementByName('htmlinput').value;
...(Bin to Dec Calc code)
}
</script>
I need some way to take an input from a html input form and send it to the script when i click the button 'go'.
First of all, input is a non-closing tag. Secondly, there's nothing like document.getElementByName, use document.getElementsByName instead or even better - assign an unique id identifier to your input and then catch it by document.getElementById.
function runbintodec() {
var bin = document.getElementsByName('htmlinput')[0].value;
}
<input placeholder="00000000" name="htmlinput">
<input id="clickMe" type="button" value="Go" onclick="runbintodec();">

Javascript max and min not working

I am trying to create a page that lets the user enter three numbers, and have the max and min values printed below from the input. I've used both the Math.max/min functions and also tried an if statement but When I click submit nothing shows up. Some insight would be greatly appreciated, thanks!
function max() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var z = document.getElementById("num3").value;
var maximum = Math.max(parseInt(x), parseInt(y), parseInt(z));
document.getElementById("max").innerHTML= maximum;
}
function min() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var z = parseInt(document.getElementById("num3").value);
document.getElementById("min").innerHTML = Math.min(x,y,z);
}
And here is my html
<p>Enter First Number:</p>
<input type="text" name = "number1" id="num1"><br>
<p>Enter Second Number</p>
<input type="text" name = "number2" id="num2"><br>
<p>Enter third number</p>
<input type="text" name = "number3" id="num3"><br>
<input type="submit" value="Submit" onclick="max(); min(); "><br />
<p>Max =</p><p id ="max"></p><br />
<p>Min =</p><p id ="min"></p><br />
replace <input type="submit"/> to <button type="submit" value="" onclick="minmax();">Submit</button>
and add JS function:
function minmax() {
min();
max();
}
Your problem seems related to how you are attaching your event.
It works OK when I use:
document.querySelector( '[type="submit"]' ).addEventListener( 'click', function() {
max();
min();
}, false );
http://jsfiddle.net/yemxrmqq/
You just need to change the tag related to the button, instead of:
<input type="submit" value="Submit" onclick="max(); min(); "><br />
just put:
<button type="submit" value="Submit" onclick="max(); min()">Click</button><br />
None of the answers here tell you why your code didn't work.
Identifiers in inline listeners are first resolved as properties of the element on which they are placed. Input elements have a default max attribute, so within an inline listener, the identifier max will reference the input's max property. Hence in any document:
<input onclick="console.log(max)">
shows '' (i.e. empty string).
So you can either change the names of the functions to something more meaningful, or change the context from which they are called so that the identifiers aren't resolved on the element, and the OP code works. e.g.
<input type="submit" value="Submit" onclick="callBoth()">
and
function callBoth() {
max();
min();
}
Incidentally, an input type submit outside a form is just a button, so you should use:
<input type="button" ...>

Global Arrays value assigning issue

I am trying to assign values to div by a global array (in ascending function) . but the array is always empty in ascending function. Please also mention the best practice in this case.
I wish to set an array in one function , and in the other function I wish to use the same populated array . but after entering all the values I found that page get refresh and the values assign to array and Hidden1 field are set to empty again.
<html>
<head>
<script type="text/javascript">
var array = new Array();
function get_strings(m)
{
i = 1;
do
{
var ArrayElement=prompt("Please Enter a Number");
i++;
array.push(ArrayElement);
}
while (i <= m);
document.getElementById('print').InnerHtml = array;
document.getElementById('Hidden1').value = array;
};
</script>
<script>
function ascending()
{
var x = document.getElementById('Hidden1').value;
document.getElementById('print').InnerHtml = x;
};
</script>
</head>
<body>
<h2>Enter Number of elements</h2>
<br /><br />
<form>
<input id="Hidden1" type="hidden" value="" />
<input id="num" type="text" name="elements"> <br> <input type="submit" value="Submit" text= "Take Input" onclick="get_strings(document.getElementById('num').value)">
<br />
<input type="submit" value="Ascending" text= "Ascending" onclick="ascending()">
</form>
<div id="print"></div>
</body>
</html>
Page got refreshed because you are clicking the submit button, it's just the basic desired behavior when clicking on a submit button. Which brings the question, do you intend to submit this value to the backend? If so what you need to do is to have your backend return the value after the form POST.
If you do not intend on submitting this value, then use a regular button instead of a submit button.

Take input value and display in another div

I cant for the life of me figure out why the following is not working. I took if from the W3school example here.
Basically I want to take the value from the input text when it changes and modify another div to include the value. I only want the div to show the new value, but I do want it to change it each time so I figured the onchange was the way to go.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + x.value;
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<div id="divID"></div>
</body>
</html>
Thanks in advance for all the help on this one.
You have 2 problems, first is that x is undefined.
second you should use another trigger for this for this to happen each time.
try this out:
function myFunction()
{
var input = document.getElementById('fname')
var div = document.getElementById('divID');
div.innerHTML = div.innerHTML + input.value;
}
and change your html to:
<input type="text" id="fname" onkeypress="myFunction()">
x is undefined in your function, it should be document.getElementById('fname').
And if you want to change the div each time you press the key, use onkeyup or onkeypress instead of onchange.
You may change x.value to document.getElementById("fname").value, if I understand your question correctly.
<head>
<script type="text/javascript">
function input(){
var input_taker = document.getElementById('email').value;
document.getElementById('display').innerHTML = input_taker;
}
</script>
</head>
<form method="post" action="#">
<input type="text" name="email" placeholder="email#example.com" id="email" onchange="input()">
<input type="submit" name="save" value="save">
</form>
<div id="display"></div>
Ok, so check this out - http://jsfiddle.net/2ufnK/2/
The issue is that you need to define x here,
var x = document.getElementById("fname");
x now references to the html object.
Then you can just call the, ".value", method to get its text. Then everything else works the way you've written it.

Categories