-1

I tried to get the input first and last name from the user, but I'm getting I'm undefined results for the both of them.

function getTextField() {
  var fname = document.getElementsByClassName("fname").value;
  var lname = document.getElementsByClassName("lname").value;

  var message = fname + "\n" + lname;
  document.getElementsByClassName("get")[0].innerHTML = message;
}
<form name="cost" autocomplete="on">
  First Name:
  <br>
  <input type="text" name="fname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25">
  <br>Last Name:
  <br>
  <input type="text" name="lname" required placeholder="Enter the last name" pattern="[A-Za-z\-]+" maxlength="25">
  <br>
  <br>
  <input type="button" onClick="getTextField()" value="Place Order!" />
  <br>
  <br> <span class="get"></span>
</form>

0

1 Answer 1

2

You're looking for the name fields by class rather than the name attribute.

Use getElementsByName instead of getElementsByClassName

function getTextField() {
  var fname = document.getElementsByName("fname")[0].value;
  var lname = document.getElementsByName("lname")[0].value;

  var message = fname + "\n" + lname;
  document.getElementsByClassName("get")[0].innerHTML = message;
}
<form name="cost" autocomplete="on">
  First Name:
  <br>
  <input type="text" name="fname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25">
  <br>Last Name:
  <br>
  <input type="text" name="lname" required placeholder="Enter the last name" pattern="[A-Za-z\-]+" maxlength="25">
  <br>
  <br>
  <input type="button" onClick="getTextField()" value="Place Order!" />
  <br>
  <br> <span class="get"></span>
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I'm new to javascript and I appreciate the help :).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.