Reputation: 13
I am trying to take the input of firstName and lastName and console log it. I know I can then add that into a box and that part works when I add it. However I can never get the values of the boxes to show up or add.
I am getting error:
Uncaught TypeError: Cannot set property 'value' of null
Basically it's simple addition but getting the value is where I am getting the issue.
function addNames() {
var a = parseInt(document.getElementById("firstName").value);
var b = parseInt(document.getElementById("lastName").value);
var answer = document.getElementById("answer");
answer.value = a + b;
}
addNames();
body {
background: #2b2b2b;
height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-family: Helvetica neue, roboto;
}
h1 {
color: #bdbdbd;
font-weight: 300;
}
form {
color: white;
}
h2 {
color: #bdbdbd;
font-weight: 200;
}
<div>
<h1 id="title"> Fill Out Form With Your Name</h1>
<form>
First name:<br>
<input type="text" name="firstname" id="firstName" value=""><br> Last name:<br>
<input type="text" name="lastname" id="lastName" value="">
</form>
<button onclick="addNames()"> Click Here</button>
<h2 id="result"></h2>
</div>
Upvotes: 1
Views: 95
Reputation: 61063
Among other issues, you don't add strings, you concatenate them. You also don't convert them to integers. Fortunately with JavaScript being loosely-typed you can use the addition operator to combine them:
var a = document.getElementById("firstName").value;
var b = document.getElementById("lastName").value;
var c = a + b;
Of course you probably want a space in there:
var c = a + ' ' + b;
Upvotes: 3
Reputation: 4182
document.getElementById("result")
and set the innerHTML.function addNames() {
var a = parseInt(document.getElementById("firstName").value);
var b = parseInt(document.getElementById("lastName").value);
var answer = a + b;
document.getElementById("result").innerHTML = answer;
}
body {
background: #2b2b2b;
height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
font-family: Helvetica neue, roboto;
}
h1 {
color: #bdbdbd;
font-weight: 300;
}
form {
color: white;
}
h2 {
color: #bdbdbd;
font-weight: 200;
}
<div>
<h1 id="title"> Fill Out Form With Your Name</h1>
<form>
First name:<br>
<input type="text" name="firstname" id="firstName" value=""><br> Last name:<br>
<input type="text" name="lastname" id="lastName" value="">
</form>
<button onclick="addNames()"> Click Here</button>
<h2 id="result"></h2>
</div>
Upvotes: 1
Reputation: 673
It looks like you have 2 issues.
addNames()
in your script. Remove that since it's blowing up on pageload.answer
but your html you have id result
And
Upvotes: 0