TransWikia.com

How do I write a script that alerts a input value given by a visitor?

Stack Overflow Asked by Mehmet Akif VARDAR on February 18, 2021

I’m a beginner in javascript. I need to code a basic script that alerts the input value given by visitor.

Here is my code:

function alertFunction() {
  var x.value = document.getElementById("student-name");
  alert(x.value);
}
<table>
  <tr>
    <td><label for="name">Student Name: </label></td>
    <td><input type="text" id="student-name"></td>
  </tr>
  <tr>
    <td><input type="button" onclick="alertFunction()" value="Enter" /></td>
  </tr>
</table>

There is something wrong. Please write me the correct one. Thanks much. Have a great day.

3 Answers

You're trying to do X.value = dom element. Do this instead

function alertFunction() {
  var x = document.getElementById("student-name").value;
  alert(x);
}
<table>
  <tr>
    <td><label for="name">Student Name: </label></td>
    <td><input type="text" id="student-name"></td>
  </tr>
  <tr>
    <td><input type="button" onclick="alertFunction()" value="Enter" /></td>
  </tr>
</table>

Correct answer by Vikrant on February 18, 2021

In Simple you can declare your button as below in td

<td><button onclick="alertFunction()">Enter</button></td>

And in Function use the below code to get the value

var x = document.getElementById("student-name").value;

Answered by Vivek Lakshmanan on February 18, 2021

You can use value property to get value of the element.

function alertFunction() {
   var x = document.getElementById("student-name").value;
   alert(x);
}

Answered by firatozcevahir on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP