2012-10-30 44 views
1

我有复选框,动态生成,当复选框被选中时,onchange方法工作正常,我的函数也被调用时,用户未选中框onchange方法调用我的意图功能的问题是,当框被选中时,页面的一部分变为活动状态,这是很好的,但是当用户取消选中该复选框时,页面的该部分再次变为活动状态,并且复选框“checked”的值保持为yes第一次检查。有没有办法检测用户何时选择取消选中,以便页面的活动部分变为非活动状态。复选框问题(使用post和onchange)

我可以发送复选框状态,而不必在表单中提交。是否需要提交邮寄才能工作?我必须为此使用Java脚本吗?

我想这我遇到的问题

<script type="text/jscript"> 
//this funciton will be called when user checks a check box. 
function edit(){ 


    //get selected category from the form 
    //var formName = 'choose'; 
    //var Category = document[formName]['choose'].value; 


    //check if browser suports ajax 
    var xmlhttp = null;  
    if(typeof XMLHttpRequest != 'udefined'){ 
     xmlhttp = new XMLHttpRequest(); 
    } 

    else if(typeof ActiveXObject != 'undefined'){ 
     xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); 
    } 

    else 
     throw new Error('You browser doesn\'t support ajax'); 


    //open connection with activateImages.php to recieve the active images as an acho 
    xmlhttp.open("GET", "activateImages.php",true);   

    //echeck if ready to recieve   
    xmlhttp.onreadystatechange = function(){ 

    if(xmlhttp.readyState == 4) 
     window.activate(xmlhttp); 
    }; 

    xmlhttp.send(null); 
    } 

    //recieve the active images then insert them in the specified location of the page. 
    function activate(xhr){ 

     if(xhr.status == 200){ 
      document.getElementById('images').innerHTML = xhr.responseText; 

     } 
     else 
      throw new Error('Server has encountered an error\n'+ 
      'Error code = '+xhr.status); 

} 

</script> 
+0

你可以使用jQuery吗? –

+0

[使用onchange复选框]的可能重复(http://stackoverflow.com/questions/13143337/check-box-using-onchange) –

回答

0

我的建议是,最好是使用图书馆一样jQuery做这种复杂的请求。主要原因是,它是跨浏览器兼容的,并且更容易实现。对于你的相同逻辑,你可以在jQuery中这样做。

首先在脚本中包含脚本。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 

接下来是AJAX GET请求和函数edit()

function edit(){ 
    $.get("activateImages.php", function(data) { 
     $("#images").html(data); 
    }).error(function(e){ 
     throw new Error('Server has encountered an error\n' + 'Error code = ' + e); 
    }); 
} 
1

变化事件处理函数不是调用,直到选中状态已更新:

<label><input type='checkbox' onchange='handleChange(this);'>Checkbox</label> 

function handleChange(cb) { 
    console.log("Changed, new value = " + cb.checked); 
} 

Example

handleChange功能会告诉你,当复选框的值会在真正的改变或假。用它来隐藏和显示你的div。

+0

谢谢你们,这是非常有益的。 – user1785939

+0

感谢阿布舍克你的解决方案很容易,它适合在 – user1785939

+0

我很高兴,它帮助。 –