Home > Enterprise >  How to select input elements and return result
How to select input elements and return result

Time:04-11

I have a form with firstname and lastname as input. I want to return full name other functions (which are working). code looks like this:

const firstName = document.getElementById("fname").value;
const lastName = document.getElementById("lname").value;
    
function fullName(firstName, lastName) {
const full = firstName   " "   lastName;
return full;
    }

. . .

function myFunction() { 
document.getElementById("result").innerHTML = fullName(firstName, lastName)   a()   b()   c()
}

it returns only the value of a() b() c().

Bonus question: I would like the console to log in this format:

fullName:
a()
b()
c()

I've tried:

//console.log(function(a, "\n",b, "\n", c));

//console.log(function({ a }, '\n', { b }, '\n', { c }));
        
//console.log(function(`${JSON.stringify(a)}
        ${b}
        ${c}`)); 
//console.log(function(`a is line 1
            b is line 2
            c is line 3`));

I have seen it works with strings or numbers, don't know how to make it work with functions.

Thanks in advance.

CodePudding user response:

You can't just declare somewhere firstname and lastname in the script and hope it updates magicly.. You have to get the information right before you want to use them

function myFunction() {
    const firstName = document.getElementById("fname").value;
    const lastName = document.getElementById("lname").value;
    document.getElementById("result").innerHTML = fullName(firstName, lastName)   a()   b()   c();
    // console.log supports "format" and %o prints objects
    console.log("a is %o b is %o c is %o", a(), b(), c());
}

CodePudding user response:

Here is an example.

const firstName = document.getElementById("fname");
const lastName = document.getElementById("lname");
const fullNme = document.getElementById("fullNname");
const getName = document.getElementById("getName");

getName.addEventListener("click", () => fullNname.value = fullName(firstName, lastName) " " otherFunction())

function otherFunction() {
  return "otherFunction";
}

function fullName(firstName, lastName) {
  return firstName.value   " "   lastName.value;
}
<input type="text" id="fname" name="fname" value="Takeshi">
<input type="text" id="lname" name="lname" value="Kovacs">
<button type="button" id="getName">
    get Name
</button>
<input type="text" id="fullNname" name="fullNname" value="">

  • Related