在GridView中,当单击复选框时,在网格的同一行中使用JavaScript将标签中的值添加到TextBox

In GridView, when click on checkbox add values from label to TextBox using JavaScript in the same row of Grid

本文关键字:JavaScript TextBox 添加 一行 标签 复选框 单击 GridView 网格      更新时间:2023-09-26

我在GridView中有3列。第一列有CheckBox,第二列有Label中的未付金额,第三列包含要支付金额的TextBox。

我的问题是,当复选框被选中时,文本框应该用第二列的值填充,而当复选框未被选中时应该清除文本框的值。

请参考我使用过的java脚本代码。

<script type="text/javascript">
          function SelectChange(ChkId, txt1, total) {
              var chk = document.getElementById(ChkId);
              UpdateField(ChkId, txt1, total)
          }
          function UpdateField(ChkId, txt1, total) {
              if (document.getElementById(ChkId).checked == true)
              {
                  var lblvalue = document.getElementById(total).value;
                  document.getElementById(txt1).innerHTML = lblvalue;
              }
              else
              {
                  document.getElementById(txt1).innerHTML = "0";
              }
          }
    </script>

在代码背后。。。

protected void grdFeesCollection_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txtPayment = (TextBox)e.Row.FindControl("txtPayment");
            Label lblDue = (Label)e.Row.FindControl("lblDue");
            CheckBox chckSelecthead = (CheckBox)e.Row.FindControl("chckSelect");
            chckSelecthead.Attributes["onclick"] = "javascript:return SelectChange('" + chckSelecthead.ClientID + "','" + "','" + txtPayment.ClientID + "','" + lblDue.ClientID + "')";
            txtPayment.Attributes["onKeyup"] = "javascript:return UpdateField('" + chckSelecthead.ClientID + "','" + txtPayment.ClientID + "','" + lblDue.ClientID + "')";
        }
    }

这不会向TextBox返回任何值,这就是问题所在。

代码隐藏:

protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e ) {
    if ( e.Row.RowType == DataControlRowType.DataRow ) {
        Label    lblDue     =    (Label) e.Row.FindControl("lblDue");
        TextBox  txtPayment =  (TextBox) e.Row.FindControl("txtPayment");
        CheckBox chckSelect = (CheckBox) e.Row.FindControl("chckSelect");
        string js = string.Format( "javascript: return SelectChange( '{0}', '{1}', '{2}' ); ", 
                                    chckSelect.ClientID, 
                                    lblDue.ClientID,
                                    txtPayment.ClientID );
        chckSelect.Attributes[ "onclick" ] = js;
    }
}

JavaScript:

function SelectChange(ChkID, DueID, PaymentID) {
    var CheckBox = document.getElementById(ChkID);
    var Due = document.getElementById(DueID);
    var Payment = document.getElementById(PaymentID);
    Payment.value = (CheckBox.checked ? Due.textContent : "");
}