duke duke - 5 months ago 24
Javascript Question

Why can't I get the correct textbox value on Razor page?

This is simple webpage with textbox and alert box to show its value on a razor view page:

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
@using (Html.BeginForm())
@Html.Label("Enter your name")
<input type="button" id="btnPost" value="Load Data using Post" />

$(document).ready(function () {
//$("#txtName").keyup(function () {
// alert(this.value);
var originvalue = $("#txtName").val();

$("#btnPost").click(function () {

I have taken the textbox value and assigned it to a var
. 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.


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();

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.