Home » Javascript » Javascript not updating @Html.TextBox

Javascript not updating @Html.TextBox

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have an Asp.Net Razor web page with a JavaScript function that isn’t updating one of my @Html.TextBox controls as intended. Here is the JavaScript:

    function UpdateDept() {
        debugger;
        var result = '';
        var badge = document.getElementById("PIP_BADGE").value;
        var url = "http://internalSite/api/personinfo/" + badge;
        alert('Using badge #' + badge)
        $.ajax({
            url: url,
            type: 'POST',
            data: { 'badge': badge },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert(JSON.stringify('result = ' + result));
                $('#PIP_DEPT').val(JSON.stringify(result));
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.responseText);
            }
        })

Both alerts give me correct values. Here is the code for the target @Html.TextBox that I want to update:

                <td style="width: 40%">
                    <div class="form-group">
                        <label for="PIP_DEPT">Department:</label>
                        <a class="anchor" id="PIP_DEPT_ANCH"></a>
                        @Html.TextBox("PIP_DEPT", @dept, new { @class = "form-control", id = "PIP_DEPT", @readonly = true, style = "width: 400px" })
                    </div>
                </td>

The initial value of @dept is assigned a value when the page is initially loaded, and it displays correctly. What am I doing wrong that the “PIP_DEPT” textbox isn’t updating?

Added to address @Mamum’s answer:
This code works, and it’s also updating a readonly field from the selected value in an @Html.DropDownList. JavaScript:

    function UpdateBadge() {
        var e = document.getElementById("PIP_USER_NAME");
        var temp = e.options[e.selectedIndex].value;
        $('#PIP_BADGE').val(temp);
    }

Textbox code:

@Html.TextBox("PIP_BADGE", @badge, new { @class = "form-control", id = "PIP_BADGE", @readonly = true, style = "width: 100px" })
Answers: