Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 28, 2023 › #Button #HowTo

How to get textbox value on button click in JavaScript

To get the value of a textbox on button click in JavaScript, you can use the .value property of the textbox element, along with an event listener on the button. The example is given below.

<input type="text" id="my-textbox" placeholder="Type Your Name"/>
<button id="my-btn">Click me</button>
<script>
  let myBtn = document.getElementById("my-btn");
  let myTextbox = document.getElementById("my-textbox");
  
  myBtn.addEventListener("click", function() {
    let textboxValue = myTextbox.value;
    console.log(textboxValue)
  });
</script>

The above code adds a click event listener to the button element. When the button is clicked, the function that is passed to addEventListener() is called. Inside that function, the .value property of the textbox element is accessed to get the value of the textbox. Then, we print the textbox value to the console using the console.log().

How to get textbox value on button click in JavaScript. #

  1. Add a click event listener to the button element directly, and then use the querySelector() method to find the textbox element and access its value property.
    <input type="text" id="my-textbox" placeholder="Type Your Name"/>
    <button id="my-btn">Click me</button>
    <script>
     document.querySelector("#my-btn").addEventListener("click", function() {
       let textboxValue = document.querySelector("#my-textbox").value;
       console.log(textboxValue);
     });
    </script>
  2. Using the document.forms collection to access the form element containing the textbox and button, and then using the elements collection to access the textbox element by name and the button element by index.
    <form>
     <input type="text" name="my-textbox" placeholder="Type Your Name"/>
     <button id="my-btn" type="button">Click me</button>
    </form>
    <script>
     let myTextbox = document.forms[0].elements["my-textbox"].value;
     let myBtn = document.forms[0].elements[1].innerText;
     console.log(myTextbox,myBtn)
    </script>
save
listen
AI Answer
Write Your Answer
loading
back
View All