复选框未取消选中

时间:2014-12-05 04:43:40

标签: javascript html ajax checkbox

我有4个复选框,并在ajax的帮助下切换插入已检查的数据并在未选中时将其删除。我能够成功插入数据,但问题在于第一个复选框,因为一旦检查就无法取消选中

<form>
<fieldset>
<input id="prof" type="checkbox" onclick="insdel('Cricket')" value="Cricket" /><span>Cricket</span>
<input id="prof" type="checkbox" onclick="insdel('Football')" value="Football" /><span>Football</span>
<input id="prof" type="checkbox" onclick="insdel('Hockey')" value="Hockey" /><span>Hockey</span>
</fieldset>
</form>

这是我的javascript

function insdel(answer) {
if(document.getElementById("prof").checked = true){
document.forms["t"]["ttq"].value= answer;
if((document.forms["t"]["ttq"].value)!=""){
var xmlhttp;    
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("list").innerHTML=xmlhttp.responseText;
}
}

xmlhttp.open("GET","pop.php?q="+answer,true);
xmlhttp.send();

}

}
else{
document.forms["t"]["ttq"].value= answer;
if((document.forms["t"]["ttq"].value)!=""){
var xmlhttp;    
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("list").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","del.php?q="+answer,true);
xmlhttp.send();

}

}
}

提前致谢

1 个答案:

答案 0 :(得分:0)

尝试使用此示例代码清楚

&#13;
&#13;
var insdel = function(chk) {
  console.log(chk.value, chk.checked, chk.id);
  if (chk.checked) {
    console.log('insert ', chk.value);
    //do the rest
  } else {
    console.log('delete ', chk.value);
    //do the rest
  }
  //do the rest
};
&#13;
<form>
  <fieldset><!-- updated ids, also the onclick parameter -->
    <input id="prof1" type="checkbox" onclick="insdel(this)" value="Cricket" /><span>Cricket</span>
    <input id="prof2" type="checkbox" onclick="insdel(this)" value="Football" /><span>Football</span>
    <input id="prof3" type="checkbox" onclick="insdel(this)" value="Hockey" /><span>Hockey</span>
  </fieldset>
</form>
&#13;
&#13;
&#13;