I am trying to pop out input box value but it is showing a blank value. why? Here is the jsfiddle.
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>
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);
});
});
$(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>