使用javascript使表单元素消失

时间:2012-07-02 15:38:25

标签: javascript python html forms

我对javascript有点新鲜。我有一堆html表单的复选框。复选框是从python脚本动态生成的。我的最后一个复选框名为“N / A”,我想这样做,如果选中任何其他复选框,“N / A”复选框会自动消失。如果选中N / A复选框,则其他复选框将消失。当然,如果我取消选中框,则应该发生相反的情况。我知道我需要为不同的id分配不同的输入字段,以便javascript可以识别它们,但我不确定如何编写javascript以使实际消失的动作发生。 谢谢。

编辑;;一些动态python代码:

print "<blockquote><strong>Labels:</strong><br/>"
for elem in output_list:
    if elem not in non_delete_list:
        print "<input type=\"checkbox\" name=\"remove_cd\" value=\"" + elem + "\" />" + elem + "<br/>"
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"r_on\" />N/A:"
print_reason_list()
print "<font color=\"#cc0000\">Reason Required</font><hr/>"

所以基本上,值为elem part的任何东西都是动态的,最后一个复选框是N / A(value =“r_on”)。

编辑2:

因为@Ankit(使用document .... style.display =“none”)所以我能够让盒子消失。我遇到的问题是,一旦选中一个方框,相应的ID将永久隐藏。为了解决这个问题,我制作了一个隐藏和取消隐藏的功能,我的onclick看起来像:

"onclick=if(this.checked){hide("NA")}else{unhide("NA")}" 

这使我可以取消选中框并重新显示相应的标签。然而,我正在遇到一个新问题。使用值elem的复选框。如果我选中两个框,然后取消选中其中一个框,则再次出现“NA”。只要有一个“elem”框被检查,我希望它保持隐藏状态。基本上,我需要重新扫描所有复选框以查看其当前状态(我认为)。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以通过javascript启用/禁用html元素:

document.getElementById('<the id of your checkbox here>').disabled = true;

对于您的情况,只需在动态复选框周围添加div标签,然后根据需要添加/删除该div。

实施例: -

print "<blockquote><strong>Labels:</strong><br/>"

for elem in output_list:
    if elem not in non_delete_list:
        print "<div id=\"listBox\" >"
        print "<input type=\"checkbox\" name=\"remove_cd\" value=\"" + elem + "\" onclick=\"if(this.checked){myFunction("upperChkBoxes")}\" />" + elem + "<br/>"
        print "</div>"
print "<input type=\"checkbox\" name=\"remove_cd\" value=\"r_on\"  onclick=\"if(this.checked){myFunction("NA")}\"  />N/A:"
print_reason_list()
print "<font color=\"#cc0000\">Reason Required</font><hr/>"


function myFunction(par){
// put your logic of add/remove here based on par value as "upperChkBoxes" or "NA"
}

希望有所帮助。

答案 1 :(得分:2)

您可以使用css属性display none

来显示或隐藏html元素

让它消失

document.getElementById('<the id of your checkbox here>').style.display = "none";

或显示回来

document.getElementById('<the id of your checkbox here>').style.display = "block";

如果您使用的是jquery,您可以轻松地使用它来完成相同的

$('#id of the checkbox').hide() or $('#id of the checkbox').show()