skip to Main Content
<input type="text" class="search-bar" placeholder="Search">
<button onclick="show()">Show Your Text</button>
var x = document.getElementsByClassName("search-bar")[0].value;
function show(){
alert(x);
}

problem
in alert function the not show anything which i write in text box

The value which i write in textbox is show in alert box function

5

Answers


  1. Try this

    <input type="text" class="search-bar" placeholder="Search">
    <button onclick="show()">Show Your Text</button>
    
    <script>
    function show() {
      var x = document.getElementsByClassName("search-bar")[0].value;
      alert(x);
    }
    </script>
    
    Login or Signup to reply.
  2. you need to retrieve the value of the input field inside the show() function.

    <input type="text" class="search-bar" placeholder="Search">
    <button onclick="show()">Show Your Text</button>
    
    <script>
    function show() {
      var x = document.getElementsByClassName("search-bar")[0].value;
      alert(x);
    }
    </script>
    
    Login or Signup to reply.
  3. You need to do two things to get this done:

    1. Put js code into <script> tag.
    2. Put this below code into show() function so that the alert text will display dynamically when clicking the button.
    var x = document.getElementsByClassName("search-bar")[0].value;
    
    <input type="text" class="search-bar" placeholder="Search">
    <button onclick="show()">Show Your Text</button>
    <script>
      function show(){
        var x = document.getElementsByClassName("search-bar")[0].value;
        alert(x);
      }
    </script>
    Login or Signup to reply.
  4. You are assigning the value before the function is executed, that’s why it’s always blank.

    <input type="text" class="search-bar" placeholder="Search">
    <button onclick="show()">Show Your Text</button>
    
    <script>
        
        function show(){
            var x = document.getElementsByClassName("search-bar")[0].value;
        alert(x);
        }
        problem
    </script>
    
    Login or Signup to reply.
  5. try to declare variable "x" in the function only, because when you click on the button onClick event gets triggered and runs the show button, and inside the show function at that moment we have an undefined value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search