2

I have two input fields and I want to add the value of one them to another. Here is what I have so far:

HTML

<input id="server" type="text" value="www.google.com">
<input id="port" type="text">
<button onclick="appendPort()">Save</button>

Javascript

function getPort() {
 let portValue = document.getElementById('port').value;
}
function appendPort(portValue) {
 getPort();
 console.log(portValue);
}

So onClick, I'm expecting the value of the first input field to be www.google.com123 if the value of the second input field is 123. Why does portValue log as undefined?

asked Oct 2, 2017 at 20:05

3 Answers 3

2

appendPort doesn't recieve an argument. It should use the return value of getPort:

function appendPort() {
 var portValue = getPort(); // get the value returned by getPort and store it in portValue
 console.log(portValue);
}

and getPort should return it:

function getPort() {
 return document.getElementById('port').value; // return something to be used by appendPort
}
answered Oct 2, 2017 at 20:08
Sign up to request clarification or add additional context in comments.

3 Comments

functions need to return things.
@RalphDavidAbernathy Ooops! Didn't notice that getPort should return the value.
@RalphDavidAbernathy You should really read about functions.
0

First of all, the portValue local variable in the getPort, so it is not alive in appendPort function. You should use it as global. Second, you using portValue as parameter in the appendPort function, so it hide the original portValue. You called the appendPort without parameter, so in the function it will be default undefined.

Try this:

<script>
let portValue = 3; // set to global
function getPort() {
 portValue = document.getElementById('port').value;
}
function appendPort() { // without parameter
 getPort();
 console.log(portValue);
}
</script>
<input id="server" type="text" value="www.google.com">
<input id="port" type="text">
<button onclick="appendPort()">Save</button>
answered Oct 2, 2017 at 20:16

Comments

0

portValue is undefined because the function getPort does not return anything. At the end of the function, add the line return portValue; Then change appendPort so that it takes no input and add this line at the beginning var portValue = getPort();

answered Oct 2, 2017 at 20:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.