开发者

What's wrong with my JavaScript? (C#/ASP.NET)

开发者 https://www.devze.com 2023-01-26 17:14 出处:网络
Here is my JavaScript: <script type=\"text/javascript\"> function onholdev(index) { var chk = document.getElementById(\'<%=grdCons.Rows[\' + index + \'].FindControl(\"chkHold\").ClientID %&g

Here is my JavaScript:

<script type="text/javascript">
function onholdev(index) {
    var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
    var txt = document.getEl开发者_如何学JAVAementById('<%=grdCons.Rows[' + index + '].FindControl("txtReason").ClientID %>');


    if (chk.checked == true) {
        txt.disabled = false;
    }
    else {
        txt.disabled = true;
        txt.value = "";
    }
}
</script>

The 'index' variable comes from the RowDataBound event of my GridView, like so:

  CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
  chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");

However, I'm getting 'too many characters in string literal' in the first line of my function (beginning with var chk). Why is this?


You're mixing client and server-side script...you just can't do this. This is executed server-side:

grdCons.Rows[' + index + '].FindControl("chkHold").ClientID

But you're calling it client-side and trying to pass an ID, that's just not something you can do, look at your rendered JavaScript function and this will be much clearer. Instead just use the ID of the table, then you can find your controls that way, for example:

var row = document.getElementById("grdCons").rows[index];
var inputs = row.getElementsByTagName("input");
//then filter by ID match, class, whatever's easiest and set what you need here


That's probably because ASP.NET throws an error, which is written in the client side call of getElementById. The onholdev function is executed client - side, and so cannot pass the index parameter to ASP.NET which is executed server - side. Try this:

<script type="text/javascript">
function onholdev(checkbox, textbox) {
    var chk = document.getElementById(checkbox);
    var txt = document.getElementById(textbox);

    if (chk.checked == true) {
        txt.disabled = false;
    }
    else {
        txt.disabled = true;
        txt.value = "";
    }
}
</script>

Replacing your server - side code with this:

CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev('" + 
    e.Row.FindControl("chkHold").ClientID + "','" + 
    e.Row.FindControl("txtReason").ClientID + "')");


The problem is your use of the single quote characters in ' + index + '. Change those to double qoutes and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消