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?
3 Answers 3
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
}
3 Comments
return things.getPort should return the value.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>
Comments
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();