Input box value is showing blank on button click

I am trying to pop out input box value but it is showing a blank value. why? Here is the jsfiddle.

$(document).ready(function() {

  var name = $("#name").val();
  $('#showName').click(function() {
    alert(name);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" placeholder="First Name">
   
<button type="button" id="showName">Show name</button>

Answers:

Answer

when you initialize var name in document.ready(), the name variable give a value of input at load of page, so value of name equals to nothing (empty string). so you must change your code that your input value read when button is clicked.

$(document).ready(function() {
    $('#showName').click(function() {
        var name = $("#name").val();
        alert(name);
    });
});
Answer

Move the var name = $("#name").val(); inside your click function.

$('#showName').click(function() {
  var name = $("#name").val();
  alert(name);
});

Example below

$(document).ready(function() {

  $('#showName').click(function() {
    var name = $("#name").val();
    alert(name);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" placeholder="First Name">
<br>
<button type="button" id="showName">Show name</button>

Answer

$(document).ready(function() {

 
  $('#showName').click(function() {
    alert($("input").val());
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" placeholder="First Name">
   
<button type="button" id="showName">Show name</button>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.