我试图根据用户输入和元素类在我的屏幕上使多个<td>
字段可见或不可见。我正在使用 jquery、html 和 javascript。
基本上,我有一个包含不同字段的 HTML 表格。我希望这些字段具有“可见”、“可见和必需”或“不可见”类。当用户选择一个选项时,它会通过删除前一个元素并添加新元素来更改该元素的类。这些字段的 onload 默认值应该是不可见的。
HTML:
<body onload="ShowTheScreen()">
<table border="1">
<tr>
<td class="ReasonCode" align="center">
<span class="FieldLabel">Reason Code</span>
</td>
<td class="CostCenter" align="center">
<span class="FieldLabel">Cost Center</span>
</td>
</tr>
<tr>
<td class="ReasonCode" align="center">
<input type="text" id="ReasonCode" name="ReasonCode" value="1243">
</td>
<td class="CostCenter" align="center">
<input type="text" id="CostCenter" name="CostCenter" value="00123">
</td>
</tr>
</table>
<input type="button" value="MakeVis" onclick="PopulateTable()">
</body>
Javascript:
function ShowTheScreen(){
ToggleFieldVisibility(".ReasonCode", 3);
ToggleFieldVisibility(".CostCenter", 3);
DisplayFields();
}
function PopulateTable(){
ToggleFieldVisibility(".ReasonCode", 2);
ToggleFieldVisibility(".CostCenter", 1);
DisplayFields();
}
function ToggleFieldVisibility(element, x){
switch(x){
case 1:
$(element).removeClass("Invisible Required").addClass("Visible");
break;
case 2:
$(element).removeClass("Invisible").addClass("Visible Required");
break;
case 3:
$(element).removeClass("Visible Required").addClass("Invisible");
break;
default:
$(element).removeClass("Visible Required").addClass("Invisible");
break;
}
DisplayFields();
}
function DisplayFields(){
$(".Invisible").css({"visibility":"hidden"});
$(".Visible").css({"visibility":"visible"});
}
The problem I'm having is this: When I open the page, the fields get the "Invisible" class added to them as they should be and they become hidden. But when I try and remove the invisible class later and add the visible class, the invisible class is never removed and the visible class is never added: the elements simply retain the classes they had at first, and therefore stay hidden.
I saw previous threads relating to problems with jquery add/removeClass, but none that seemed to help me out. Let me know if you need more info.
UPDATE 1: Thanks for all the replies, everyone! Unfortunately, and I thought this would happen, the code I posted here is a far simplified version of the code I actually have and most of the answers I've received seem to be related to the syntax posted--like the issue with the quotes. I've updated the code to better reflect what I'm really doing. Hopefully this will narrow down what the issue is.
UPDATE 2: I know what I was doing wrong. In my code I have shown here I'm calling ToggleFieldVisibility(".ReasonCode", 2), which works fine. But in my actual code, I was retrieving the number 2 from a SQL call using an outside application, and it was returning it as a string. The "2" would get compared to 2 in the switch (or "1" to 1 and "3" to 3) and always go to default, so that's why those fields always came up invisible. Hah!