Reputation: 1874
This is simple webpage with textbox and alert box to show its value on a razor view page:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
@using (Html.BeginForm())
{
<div>
@Html.Label("Enter your name")
@Html.TextBox("txtName")
</div>
<input type="button" id="btnPost" value="Load Data using Post" />
<script>
$(document).ready(function () {
//$("#txtName").keyup(function () {
// alert(this.value);
//});
var originvalue = $("#txtName").val();
$("#btnPost").click(function () {
alert(originvalue);
});
});
});
</script>
}
</body>
</html>
I have taken the textbox value and assigned it to a var originvalue
. Now I want to show this value in an alert box. Is this some kind of bug? I can't figure out what is missing here.
Upvotes: 1
Views: 1178
Reputation: 352
Please replace your
$("#btnPost").click(function () {
alert(originvalue);
});
with
$("#btnPost").click(function () {
alert($("#txtName").val());
});
Upvotes: 1
Reputation: 337713
The problem is because you only set originvalue
when the page loads and the input
has no value in it. If you want to retrieve the value the user typed, set that variable inside the click handler:
$(document).ready(function () {
$("#btnPost").click(function () {
var originvalue = $("#txtName").val();
console.log(originvalue);
});
});
Also note that your original JS code has one set of closing braces/brackets too many, and you should also use console.log()
to debug over alert()
because the former does not coerce data types.
Upvotes: 3