Home > Back-end >  Get the value of textbox in jaavscript
Get the value of textbox in jaavscript

Time:11-29

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" ><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname">
  <button type="button" id="butt">click here </button>
</form>
<script>
  const lname=document.getElementById('lname').value;
  const fname=document.getElementById('fname').value;
  document.getElementById('butt').onclick= function() {submit();}
  function submit(lname,fname){
      alert(lname);
      console.log(fname);
  }
</script>

I know this is kiddish. I've been trying to get the value inside a html input box and alert it using js. Its returning as undefined error. Any help is appreciated

CodePudding user response:

The two issues I'm seeing are:

  1. The submit function is expecting two arguments which aren't being supplied when calling it.
  2. You're reading the values of the inputs immediately when the page loads, before the user has had a chance to type anything.

Remove the function arguments entirely and read the values in the function, after the user has clicked the button. For example:

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" ><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname">
  <button type="button" id="butt">click here </button>
</form>
<script>
  document.getElementById('butt').onclick= function() {submit();}
  function submit(){
      // define and read the values here
      const lname=document.getElementById('lname').value;
      const fname=document.getElementById('fname').value;

      alert(lname);
      console.log(fname);
  }
</script>

CodePudding user response:

The reason why it is returning undefined is because you have arguments which are never used.

Answer Below:

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname">
  <button type="button" id="butt">click here </button>
</form>
<script>
  var lname = document.getElementById('lname');
  var fname = document.getElementById('fname');
  var btn = document.getElementById('butt');

  btn.onclick = function() {
    submit();
  }

  function submit() {
    alert(lname.value);
    console.log(fname.value);
  }
</script>

You're Welcome!

  • Related