Get value from textbox and output it - javascript

How to get value from myTextbox and output to <p>?
Why I got the error message: [object HTMLInputElement]
<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>
<script>
function myFunction() {
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x;
}
</script>

You get this error message because x is an object. This means that he is complex (textbox have value, name, onclick, etc) and don't know how/what to be represented as string. The result is his type [object HTMLInputElement].
To get the value of the object you have to acces x.value property.
function myFunction() {
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;
}
<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>

To extract data from control you have to use .value
Try like this
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;

Access the text in the input using .value:
<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>
<script>
function myFunction() {
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;
}
</script>
For fun, you can update the <p> automatically:
<input type="text" id="myTextbox" onchange="myFunction()" onkeyup="this.onchange();">
<p id="myOutput"></p>
<script>
function myFunction() {
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;
}
</script>

You need to fetch value of textbox and then feed it to the paragraph tag.
You got the error because you are trying to insert textbox in paragraph.
function myFunction() {
var x = document.getElementById("myTextbox");
document.getElementById("myOutput").innerHTML = x.value;
}
<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>

<input type="text" id="myTextbox">
<input type="button" id="myButton" value="Run" onclick="myFunction()">
<p id="myOutput"></p>
<script>
function myFunction() {
var x = document.querySelector("#myTextbox");
document.querySelector("#myOutput").innerHTML = x.value;
}
</script>

You have missed out the value of the input field, Try this fiddle
var x = document.getElementById("myTextbox").value;

Related

How do I delete document.write() out of my calculator

How do I make this calculator display the result on the first page after the ='s sign without destroying all of the html on the page with document.write()?
I know that document.write() is the problem, but I don't know of anything else to use. I'm very new to coding, so any help is greatly appreciated.
I also have a problem with the division part because it is putting the result right next to the remainder, however, once the document.write() problem is resolved, I think that the solution should become more apparent. Thank You!
<head>
<script language="javascript" type="text/javascript">
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.write(result);
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.write(result)
document.write(remainder)
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.write(result);
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.write(result);
}
</script>
<title>java</title>
</head>
<body>
Addition
<p>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
</p>
<p>
Subtraction
<p>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<p>Multiplication
<p>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
</p>
<p>Division
<p>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
</p>
</body>
</html>
You can either use textContent or innerHTML.
Here's an example using textContent:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').textContent = result;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').textContent = result;
document.getElementById('divide-remainder').textContent = remainder;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').textContent = result;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').textContent = result;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
With textContent you can only set text, with innerHTML you can set HTML:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').innerHTML = `<i style="color: blue">${result}</i>`;
document.getElementById('divide-remainder').innerHTML = `<i style="color: blue">${remainder}</i>`;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
It's worth noting, with innerHTML there are security concerns as mentioned here:
...there are ways to execute JavaScript without using elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use Node.textContent. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
Here are some other methods used to manipulate the DOM:
insertAdjacentElement
innerText
insertAdjacentHTML
insertAdjacentText
insertBefore
appendChild
replaceChild
removeChild
nodeValue
outerHTML
outerText
remove
See the full list here.
As you have discovered, document.write() is tricky because it has a tendency to overwrite the existing content when used. Let's see what the documentation has to say about it:
Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.
Hmm, well what else can we do? Fortunately, it is possible to target specific parts of the page and replace content in those elements only. So, for example we could add <span> elements with ids like #add-result, #div-result etc to the page which will contain the results of their respective action. Then, instead of using document.write() to output the results, we can replace the content in those elements.
Let's add a <span> to contain our add result:
Addition<p>
<input type="text" id="t1" name="t1" /> +
<input type="text" id="t2" name="t2" />
<input type="button" id="add" value="=" onClick="add();" />
<span id="add-result></span>
</p>
(Note: remember to close your <input /> tags with a />!)
How do we target a specific element? With document.querySelector(). Docs
Then, we can easily change the content inside of that element by updating the element.textContent property, just like you would a variable:
function add(){
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1+input2;
// get the element with the #add-result ID
var element = document.querySelector("#add-result");
// update the content in that element
element.textContent = result;
}
Now when you add two numbers together and press =, the result will appear inside of the <span id="add-result"></span> element instead of overwriting the entire page. See if you can get it working for the other inputs as well. Remember you will need a unique id for each element you want to display a result in, and update the calculation functions accordingly!

When I enter something into the form, it returns as undefined

function outputItem() {
var x = document.getElementById("form1");
var item = x.elements["item"].value ;
document.getElementById("output").innerHTML = item ;
}
<div>
<p id="output"></p>
</div>
<form id="form1">
item: <input name="item" type="text" size="20">
</form>
<button onclick="outputItem()">Add</button>
elements is a NodeList containing all the form controls in the form.
Normally, it will have a property named foo to go with a form control with name="foo".
However, you are using the name item which has a predefined value on NodeList so when you access it you get that function and not the form control.
This would have been more obvious had you debugged the code with console.log(x.elements["item"]).
Avoid using the elements NodeList. Use something else, such as querySelector instead.
function outputItem() {
var item = document.querySelector('#form1[name="item"]'].value ;
document.getElementById("output").innerHTML = item ;
}
use :
var item = x.elements.namedItem("item").value ;
function outputItem() {
var x = document.getElementById("form1");
var item = x.elements.namedItem("item").value ;
document.getElementById("output").innerHTML = item ;
}
<div>
<p id="output"></p>
</div>
<form id="form1" >
item: <input name="item" type="text" size="20">
</form>
<button onclick="outputItem()">Add</button>
Because you're accessing the wrong element's value. You should directly get the input element you are inserting value in.
<!DOCTYPE html>
<html>
<body>
<div>
<p id="output"></p>
</div>
<form id="form1">
item: <input id="input1" name="item" type="text" size="20">
</form>
<button onclick="outputItem()">Add</button>
</body>
<script type="text/javascript">
function outputItem() {
var x = document.getElementById("input1");
var item = x.value;
document.getElementById("output").innerHTML = item ;
}
</script>
</html>

how to increment and decrement the text box value using javascript?

i am trying increment and decrement a number if user is giving in text box is 15 it should be incremented when click a button and also decrement when button clicking...
this is my javascript code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function incNumber() {
for(i=1;i>0;i++){
document.getElementById("display").value=i;
}
}
function decNumber() {
for(i=1;i>0;i--){
document.getElementById("display").value=i;
}
}
</script>
</head>
<body>
<form>
<input type="text" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
</form>
</body>
</html>
Use parseInt() function to convert the value from string to integer.
function incNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c++;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
The logic stands for decNumber()
function decNumber(){
var c = parseInt(document.getElementsByTagName("input")[0].value);
c--;
document.getElementsByTagName("input")[0].value = c;
document.getElementById("display").innerHTML = c;
}
Few suggestions
1.Never mix up your markup with javascript. Consider attaching events click/change at javascript end
DOM search is costly.use it cautiously
3.Use parseInt(variablename,10) ->to convert it into integer
check the following snippet
window.onload=function(){
var incButton=document.getElementById("inc");
incButton.addEventListener("click",incNumber);
var decButton=document.getElementById("dec");
decButton.addEventListener("click",decNumber);
}
function incNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
if(value==15){
displayValue.innerHTML=value+1;
}
}
function decNumber() {
var displayValue= document.getElementById("display");
var text=document.getElementById("input");
var value=parseInt(text.value,10);
displayValue.innerHTML=value-1;
}
<form>
<input type="text" value="0" id="input"/>
<input type="button" value="Increase" id="inc" />
<input type="button" value="Decrease" id="dec" />
<label id="display"></label>
</form>
Hope this helps
If you want to increment the label value by the input value try this
function incNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)+$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
function decNumber(){
var num=0;
if(isNaN(document.getElementById('diplay').innerHTML)){
num=$("#inputVal").val();
}
else{
num=parseInt(document.getElementById('diplay').innerHTML)-$("#inputVal").val();
}
document.getElementById('diplay').innerHTML=num;
}
In HTML
<form>
<input type="number" id="inputVal" value="0"/>
<input type="button" value="Increase" id="inc" onclick="incNumber()"/>
<input type="button" value="Decrease" id="dec" onclick="decNumber()"/>
<label id="display"></label>
or you can define input type as number
<input type="number" id="numbrfield"/>
you will automatically get buttons to increment or decrement when you hover on the field.

How do I tie html inputs into my javascript function?

<!DOCTYPE html>
<html>
<body>
<form>
Birth Year:<br>
<input type="number" name="birthYear">
<br>
Current Year:<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
<script>
function calculateAge(ghF, xhF) {
var ghF = "birthYear"
var xhF = "currentYear"
return (xhF - ghF);
} {
document.getElementByID("output").innerHTML = text;
};
</script>
</body>
When I click on the button it should print out "You are x age". Where would I add that text? At the moment nothing happens when I click on the button.
getElementById will return the DOM element having id as mentioned argument. .value is property of input element which will give the value of input
Instead of returning value, you must set the innerHTML/innerText after doing subtraction.
Note: You must assign unique id attributes to the element to retrieve DOM element.
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML = xhF - ghF;
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear" id="birthYear">
<br>Current Year:
<br>
<input type="number" name="currentYear" id="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML="You are " +(xhF - ghF) + " age";
}
EXAMPLE
The function is badly formed.
This will do the trick:
function calculateAge() {
var ghF = document.querySelector('[name="birthYear"]').value;
var xhF = document.querySelector('[name="currentYear"]').value;
document.getElementById("output").innerHTML = "You are "+(xhF - ghF)+" age";
}
<form>
Birth Year:
<br>
<input type="number" name="birthYear">
<br>
Current Year:
<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>

Why it is not printing the character in a paragraph?

Write a script that inputs an integer code for a character and displays the corresponding character.
It should print in a paragraph.
function character() {
var input = document.getElementById( "input" );
var code = document.getElementById( "output" ).innerHTML = input;
output.value = String.fromCharCode( code );
}
<input id="input" type="text" size="10">
<br>
<input type="button" value="click here" onclick="character()" id="button">
<br>
<p id="output" ></p>
A P is not a form element. Also if you use form.fieldName, you need to use name="" instead of id=""; otherwise use document.getElementById for all fields and ignore the form.
You need to use innerHTML or innerText/textContent for a paragraph
document.getElementById("output").innerHTML=...
function character() {
var form = document.getElementById("form");
var code = parseInt(form.input.value,10); // radix 10 to make decimal
document.getElementById("output").innerHTML = String.fromCharCode(code);
}
<form id="form">
<input name="input" type="text" size="10">
<br>
<input type="button" value="click here" onclick="character()" id="button">
<br>
<p id="output" ></p>
</form>
You have the problem for access to the elements inside a form.
document.getElementById("form").elements['input']
But this only works with form elements, not with other HTML elements.
In this of elements, you can use id or name but for historical reasons.
You have another way here:
function character() {
var input = document.getElementById("input"),
output = document.getElementById("output");
output.innerHTML = String.fromCharCode(parseInt(input.value), 10) || '';
}
<form id="form">
<input id="input" type="text" size="10">
<br>
<input type="button" value="click here" onclick="character()" id="button">
<br>
<p id="output" ></p>
</form>
Here, this works:
<script>
function character() {
var ChrCode = document.getElementById("input").value;
document.getElementById("output").innerText = ChrCode + " = " + String.fromCharCode(ChrCode);
//output.value = String.fromCharCode( code );
}
</script>
<input id="input" type="text" size="10">
<br>
<input type="button" value="click here" onclick="character()" id="button">
<br>
<p id="output" >Output</p>

Categories