Home > Software engineering >  How can I concatenate multiple user inputs in JS?
How can I concatenate multiple user inputs in JS?

Time:01-31

I am just starting out but I am stuck in what many will likely find to be a simple problem. I am trying to have multiple inputs concatenate after a button is pressed at the end.

Here is the code I tried but only "fname" shows up after I click the button instead of the value that was input into the space. What am I missing?

<!DOCTYPE html>
<html lang="en">

<body>

  <p> Please enter your First Name: <input type="text" id="fname"></p>
  <p> Please enter your Last Name: <input type="text" id="lname"></p>
  <p> Please enter your User ID: <input type="text" id="uid"></p>
  <p> Please enter your date of birth: <input type="date" id="bday"></p>

  <button onclick="getEls()">Click Here<br>
        When Done</button>

  <script>
    function getEls() {
      document.getElementById("answer");
      answer.innerHTML = (Hello   "fname"   " "   "lname"   your user id is " uid"   and your birthday is   "bday".);
    }
  </script>

  <p id=answer>
    <p>

</body>

</html>

CodePudding user response:

I don't know if I understand well your question but is that what you want?

function getEls() {
      var answer = document.getElementById("answer");
      var fname = document.getElementById("fname").value;
      var lname = document.getElementById("lname").value;
      var uid = document.getElementById("uid").value;
      var bday = document.getElementById("bday").value;
      answer.innerHTML = ("Hello "   fname   " "   lname   " your user id is "   uid   " and your birthday is "   bday   ".");
    }
<!DOCTYPE html>
<html lang="en">

<body>

  <p> 
    Please enter your First Name: 
    <input type="text" id="fname">   
  </p>
  
  <p> 
    Please enter your Last Name: 
    <input type="text" id="lname"> 
  </p>
  
  <p> 
    Please enter your User ID: 
    <input type="text" id="uid">
  </p>
  
  <p> 
    Please enter your date of birth: 
    <input type="date" id="bday">
  </p>

  <button onclick="getEls()">
    Click Here<br>
    When Done
  </button>

  <p id=answer>
  <p>

</body>

</html>

If you have any questions please tell me in the comment

CodePudding user response:

Your errors were a combination of typos (which would be a valid close reason), and a misunderstanding of how to use HTML <input> elements, and their values, in a String.

First, we'll look at the mistakes:

function getEls() {
  // here, you retrieve an element correctly but don't
  // assign it to a variable, and you do nothing with it;
  // this is valid JavaScript, and not necessarily an error,
  // but it's entirely pointless:
  document.getElementById("answer");

  // the reason that this works is the legacy of a terrible
  // decision by Microsoft - years ago - to make any element
  // with an id an automatic global variable, with the variable-
  // name being the (unique) id of that element. This is
  // a common implementation, but not listed in the spec so
  // it may change in future; don't rely on the behaviour (and
  // ideally don't use global variables):
  answer.innerHTML = 
    // here you have hard-coded String components to which
    // you want to interpolate/concatenate your supplied
    // variables; unfortunately (for reasons unknown) you chose
    // to leave the String unquoted (so, in JavaScript, these
    // become undeclared variables), and you've quoted the
    // variable names (and a lone white-space):
    (Hello   "fname"   " "   "lname"   your user id is " uid"   and your birthday is   "bday".);
    // Also, you seem to have a ' ' operator missing, which
    // contributes to the 'missing ) in parenthetical' error.
}

To correct this:

<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>

<button onclick="getEls()">Click Here<br>
      When Done</button>

<script>
  function getEls() {
    let answer = document.getElementById("answer"),
      fname = document.getElementById('fname'),
      uid = document.getElementById('uid'),
      bday = document.getElementById('bday');

    answer.innerHTML = ("Hello"   fname.value   " "   lname.value   "your user id is "   uid.value   " and your birthday is "   bday.value   ". ");
  }
</script>

<p id=answer></p>

JS Fiddle demo.

Now, while that works, we're going to refine it towards code that's more DRY (don't repeat yourself), and also towards unobtrusive JavaScript, which moves the event-handling out of the HTML:

// using a simple named function, using Arrow syntax, to retrieve an element
// via its assigned 'id' attribute-value (this is optional, but personally I
// don't like typing 'document.getElementById(...)' more than once):
const dGEBI = (id) => document.getElementById(id),
            // your function, declared as a constant (on the assumption you're
      // unlikely to redefine the function through the lifetime of your
      // page):
            getEls = function () {
        // we retrieve the various elements, and assign them to
        // variables:
                let answer = dGEBI('answer'),
                // we retrieve the <input> elements, and cache their values:
                fname = dGEBI('fname').value,
            lname = dGEBI('lname').value,
            uid = dGEBI('uid').value,
            bday = dGEBI('bday').value;
        
        // here we use a template-literal to construct the String; this is
        // delimited by backticks; and we can directly interpolate JavaScript
        // variables or the results of JavaScript expressions into the String,
        // by wrapping them with curly-braces ('{...}') and prefixing with a '$'
        // character:'
        answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
      }

// here we use document.querySelector() to retrieve the first (if any) element matching
// the supplied CSS selector; and then use EventTarget.addEventListener() to bind
// the getEls() function (note the deliberate lack of parentheses) as the event-handler
// for the 'click' event:
document.querySelector('button').addEventListener('click', getEls);
<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>

<button>Click Here<br>When Done</button>

<p id=answer></p>

JS Fiddle demo.

Next, We'll take a look at your HTML; and use <label> elements:

const dGEBI = (id) => document.getElementById(id),
  getEls = function() {
    let answer = dGEBI('answer'),
      fname = dGEBI('fname').value,
      lname = dGEBI('lname').value,
      uid = dGEBI('uid').value,
      bday = dGEBI('bday').value;

    answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
  }

document.querySelector('button').addEventListener('click', getEls);
label {
  display: block;
}

label:last-of-type {
  display: revert;
}
<!-- Here, we've replaced the <p> elements with <label> elements; this
     allows the user to click the text of the <label> to focus the
     associated <input> element: -->
<label>Please enter your First Name: <input type="text" id="fname"></label>
<label>Please enter your Last Name: <input type="text" id="lname"></label>
<label>Please enter your User ID: <input type="text" id="uid"></label>

<!-- I've taken a different approach here, and used the 'for' attribute to
     associate the <input> and <label>; for this approach the 'for' attribute
     must contain the exact 'id' attribute-value of the relevant <input>: -->
<label for="bday">Please enter your date of birth: </label> <input type="date" id="bday">

<button>Click Here<br>When Done</button>

<p id=answer></p>

JS Fiddle demo.

References:

HTML:

  • Related