使用 JavaScript 使表单元素消失

making form elements disappear with javascript

本文关键字:元素 消失 表单 JavaScript 使用      更新时间:2023-09-26

我对javascript有点陌生。我有一堆 html 表单的复选框。复选框是从 python 脚本动态生成的。我拥有的最后一个复选框标题为"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/>"

所以基本上,任何带有 value=elem 部分的东西都是动态的,最后一个复选框是 N/A (value="r_on")。

编辑2:

因此,由于@Ankit(使用文档....style.display= "none")。我遇到的问题是,一旦选中一个框,相应的 id 就会永久隐藏。为了解决这个问题,我做了一个隐藏和取消隐藏功能,我的onclick看起来像:

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

这使我可以取消选中这些框并导致相应的标签重新出现。但是,我遇到了一个新问题。带有价值复选框。如果我选中两个框,然后取消选中其中一个框,则"NA"再次出现。我希望它保持隐藏状态,只要有一个选中的"elem"框。基本上,我需要重新扫描所有复选框以查看其当前状态(我认为)。我该怎么做?

您可以通过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"
}

希望有帮助。

您可以使用 css 属性显示或隐藏 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()