JavaScript for GridView row TemplateFields
I'm creating a program where, in each GridView row, there is a checkbox and a textbox, which are unchecked and disabled by default respectively. When the checkbox is ticked, I need to fire a bit of JavaScript to enable that textbox, and vice versa for when is unticked. So far I am doing this:
JS:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[index].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[index].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
C# (RowDataBound event)
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
But in the JS, it's saying the 'index' variable does not exist,开发者_开发技巧 in the first line of the function (that begins with var chk). Am I doing this right?
the problem is that index is inside the string while it should be a parameter, this fixes it :
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
the same goes for the other line
Since the check box will render as input we can able to find it by using the $('.check input')
and since it is added dynamically we need to use jquery bind
to add the click function to the check box.So in this I am getting the checked control by chk = $('.check input');
.Each time when user checks a check box the function calls .I am here setting the visibility to none of all text box and when the user click it will find the next control and removing the class .hde
using $(this).parent().next().removeClass('hide');
.So the textbox will be visible next to the checkbox.
In your case I think by default you will make textbox disabled=false
.hide is used to set visiblity false.you can do disabling by adding attribute disabled to the textbox
css
.hide
{
display: none;
}
Designer Code
<ItemTemplate>
<asp:CheckBox ID="cbEnergyItems" runat="server" CssClass="check" />
<input type="text" id="txtQty" style="width: 25px" class="hide"
value="0" runat="server" />
<%# Eval("something") %>
</ItemTemplate>
Jquery
$('.check input').bind("click", function() {
var chk = $('.check input');
if ($(this).attr('checked')) {
//$(this).parent().next().removeClass('hide'); //removing the class to visible. you can do removing the attribute
$(this).parent().next().removeAttr("disabled");
if ($(this).parent().next().val() == ""0"")
showStatus(true, "Please enter the quantity");
}
else {
$(this).parent().next("disabled","disabled").
// $(this).parent().next().addClass('hide');
}
});
I think this will solve your problem.
Thanks all for your help, I sort of 'solved' it by not doing it serverside instead. Bit lazy but saves a lot of JS headaches.
精彩评论