I have two dropdown lists inside the gridview, namely ddonsiteoffsite and ddhours. Now what I want is if the selectedtext of ddonsiteoffsite is "onsite" the ddhours should be disabled. I tried the following code snippet, but it's not disabling the ddhours.
<asp:TemplateColumn HeaderText=" OnSite/OffSite" >
开发者_如何学C <ItemTemplate>
<asp:DropDownList ID="ddOnsiteOffside" runat="server" onchange="ToggleOnOff(this)"><asp:ListItem Text = "Offsite" Value="Offsite"></asp:ListItem>
<asp:ListItem Text = "Onsite" Value="Onsite"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="ddhours" runat="server">
<asp:ListItem Text = "1" Value="1" ></asp:ListItem>
<asp:ListItem Text = "2" Value="2" ></asp:ListItem>
<asp:ListItem Text = "3" Value="3" ></asp:ListItem>
<asp:ListItem Text = "4" Value="4" ></asp:ListItem>
<asp:ListItem Text = "5" Value="5" ></asp:ListItem>
<asp:ListItem Text = "6" Value="6" ></asp:ListItem>
<asp:ListItem Text = "7" Value="7" ></asp:ListItem>
<asp:ListItem Text = "8" Value="8" ></asp:ListItem>
<asp:ListItem Text = "9" Value="9" ></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
and the corresponding JavaScript I am using is:
function ToggleOnOff(ddonoff)
{
var row = chk.parentNode.parentNode;
if(ddonoff.value=="Onsite")
{
row.getElementsByTagName("ddhours")[0].disabled = true;
}
else
row.getElementsByTagName("ddhours")[0].disabled = false;
}
How can I achieve this using JavaScript or jQuery? I'm not understanding where I went wrong.
Just do this.
function ToggleOnOff(ddonoff) {
$(ddonoff)
.parent()// parent of ddl is td
.next()// gives the next td
.find('select')// finds a select element in that td
.attr('disabled', (ddonoff.value == "Onsite") ? 'disabled' : '');//enable-disable
}
OR
function ToggleOnOff(ddonoff) {
$(ddonoff)
.parent()//td
.parent()//tr
.find('select[id*="ddhours"]')//select by id
.attr('disabled', (ddonoff.value == "Onsite") ? 'disabled' : '');//disable-enable
}
Method 2 works even if the two columns are not next to each other.
Dependency: jQuery
If you are having more than one element with the same id then it will be an invalid HTML document. Remove the ids and give it a name.
Something like this
$("select[name='ddOnsiteOffsideName']").change(function(){
var parent = $(this).closest("tr");
var hoursSelectBox = parent.find("select[name='hoursName']");
if (hoursSelectBox.val() === "Onsite") {
hoursSelectBox.attr("disabled", true);
}
});
In your code you are using row.getElementsByTagName("ddhours")
. This will fetch all the elements with the tag name `ddhours' which will not be correct in this case.
精彩评论