2016-09-19 44 views
2

我正在尝试使用复选框来清除表单,但我不想重置清除复选框本身。我使用的代码如下:使用复选框清除表单

<input name="no_cage" id="no_cage" type="checkbox" value="1" onclick="this.form.reset();"> 

当我点击复选框清除它的形式很好,但不幸的是,也很清楚自己太。

该复选框还会更新一个数据库,如果选中,则为1,否则为0。所以我需要它在表单中,它需要能够在选中和未选中之间切换。

+3

使用复选框表单标签 –

+0

的你会如何再次复位形式,如果复选框选中留了下来? –

+0

该复选框也更新一个数据库,如果选中,则为1,如果未选中,则为0。所以我需要它在表单中,它需要能够在选中和未选中之间切换。 –

回答

3

有两种方法可以做到这一点:

创建一个JavaScript函数来重置表单,然后再选中该复选框为true。

使用jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).on('change', '#no_cage', function() { 
    if(this.checked) { 
     document.getElementById("client").reset(); 
     this.checked = true; 
    } 
}); 
</script> 
<form id="client"> 
    <input type="text"> 
    <input id="no_cage" type="checkbox" value="1"> CLEAR 
</form> 

使用JavaScript

<script type="text/javascript"> 
function clearform(){ 
    if (document.getElementById("no_cage").checked == true){ 
     document.getElementById("client").reset(); 
     document.getElementById("no_cage").checked = true; 
    } 
} 
</script> 
<form id="client"> 
    <input type="text"> 
    <input id="no_cage" type="checkbox" onclick="javascript:clearform();"> CLEAR 
</form> 

OR, 保持复选框表单

<script type="text/javascript"> 
function clearform(){ 
    document.getElementById("client").reset(); 
} 
</script> 
<form id="client"> 
    <input type="text"> 
</form> 
<input id="no_cage" type="checkbox" value="1" onclick="javascript:clearform();"> CLEAR 
+0

您的第一个选项部分工作,但不允许我取消选中该复选框。 –

+0

你是对的,那应该工作 – Prakash

+0

第一个选项很好。我还有一个问题,其中还有一个从数据库中提取数据并包含所选选项的选择输入。清除复选框不会删除选定的选项。我是否需要将此作为新问题发布,还是可以在此处添加它? –

1

我不中不知道你是否想这样做,但我改变了代码,如果复选框被选中而不是清除,那么它不会。下面的代码

<form id ="myForm" name = "test"> 
<input type ="text"/> 
<input type ="text"/> 
<input type ="text"/> 
<input type ="text"/> 
</form> 


<input name="no_cage" id="no_cage" type="checkbox" onclick="resetForm()"> 

<script type="text/javascript"> 

function resetForm() 

{ 
if (document.getElementById("no_cage").checked == true) 

{ 

document.getElementById("myForm").reset(); 

} 

} 
</script> 
0
<form id="myForm"> 
First name: <input type="text" name="fname"><br> 
Last name: <input type="text" name="lname"><br><br> 
<input type="checkbox" id="box"onclick="myFunction()" value="Reset form">reset 
</form> 
<script> 
function myFunction() { 
document.getElementById("myForm").reset(); 
document.getElementById("box").checked = true; 
}</script> 

希望它有助于