Elbert John Felipe
Elbert John Felipe

Reputation: 181

Passed variable from code behind to javascript not updating

I need to pass the newly selected row index of the gridview to my javascript in aspx page. But the code only fetch the initial value of the variable and when the script runs again, it contains the not updated value.

variable in my code behind is "SelectedRowIndex" which is an integer

    window.addEventListener("keydown", function (event) {
        console.log('<%= SelectedRowIndex %>');
        var validArrowKey = false;
        var index = '<%= SelectedRowIndex %>';

        if (event.keyCode == 40) {
            validArrowKey = true;
            index++;
        }
        else if (event.keyCode == 38 && index > -1) {
            validArrowKey = true;
            index--;
        }

        if (validArrowKey) {
            var trPaymentDetails = document.getElementById("trPaymentDetails_" + index.toString())

            if (trPaymentDetails) {
                __doPostBack('ctl00$MainContent$grdPaymentDetails', 'Select$' + index.toString());
            }
            else
                __doPostBack('ctl00$MainContent$grdPaymentDetails', 'Select$' + index.toString());

        }
    }, false);

To set the initial value for the selected row index, the user must click a row in the gridview first, inside that inclick trigger will set the variable to the user's selected row.

Upvotes: 0

Views: 170

Answers (1)

mortb
mortb

Reputation: 9839

Make the index variable global by moving it outside the function, then it will only be set once.

var index = '<%= SelectedRowIndex %>';
window.addEventListener("keydown", function (event) {
        console.log('<%= SelectedRowIndex %>');
        var validArrowKey = false;

        if (event.keyCode == 40) {
            validArrowKey = true;
            index++;
        }
        else if (event.keyCode == 38 && index > -1) {
            validArrowKey = true;
            index--;
        }

        if (validArrowKey) {
            var trPaymentDetails = document.getElementById("trPaymentDetails_" + index.toString())

            if (trPaymentDetails) {
                __doPostBack('ctl00$MainContent$grdPaymentDetails', 'Select$' + index.toString());
            }
            else
                __doPostBack('ctl00$MainContent$grdPaymentDetails', 'Select$' + index.toString());

        }
    }, false);

Upvotes: 1

Related Questions