Ralph David Abernathy Ralph David Abernathy - 2 years ago 206
HTML Question

How to append value of one input field into another input field's value with vanilla Javascript?

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
?

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download