Hiding Rows Via Drop Down Lists
I have this weird issue with hiding/showing rows of a table via jQuery and drop down lists. Instead of posting back data based on the filters I just want to hide the data not relevant to what's selected in t开发者_如何学Che drop down lists. Here's the snippet:
$().ready(function() {
$("#SupplierID").change(changeme);
$("#BusinessID").change(changeme);
});
function changeme() {
$("table tr").show();
$("table tr td:nth-child(2):not(:contains('" + $("#SupplierID :selected").text() + "'))").parent().hide();
$("table tr td:nth-child(6):not(:contains('" + $("#BusinessID :selected").text() + "'))").parent().hide();
return false;
}
The problem with it is that SupplierID works fine, but BusinessID only works once a SupplierID has been selected, and not before. If I go into the page and select a BusinessID from the drop down list straight away nothing happens. I have to change the SupplierID drop down list first in order for it to work. Additionally if SupplierID is set to the "All" option (blank value) then the BusinessID drop down list doesn't work.
Any ideas?
EDIT
Indeed it was an error because of a no-value thing. The thing is, this is what I have to have now:
$(function() {
$("#SupplierID, #BusinessID").change(changeme);
});
function changeme() {
$("table tr").show();
if ($("#SupplierID :selected").val()) {
$("table tr td:nth-child(2):not(:contains('" + $("#SupplierID :selected").text() + "'))").parent().hide();
}
if ($("#BusinessID :selected").val()) {
$("table tr td:nth-child(6):not(:contains('" + $("#BusinessID :selected").text() + "'))").parent().hide();
}
}
It just seems a bit nasty. Any recommendations on how to make this more elegant?
Did you check your browsers error console? If not do so.
I guess the second statement in your changeme
method will throw an error unless you have selected a SupplierID.
The selector without selected supplier would end up resolving to this I guess which probably will fail as you don't select anything on which you could call .parent().hide()
. (easy test switch second and third line and test if behaviour also switches).
$("table tr td:nth-child(2):not(:contains(''))").parent().hide();
or it already throws up on
$("#SupplierID :selected").text()
Where also nothing is selected and text()
could fail.
Just a random guess upon a quick look at the provide source without testing. Or something else in your code is failing.
精彩评论