Javascript会自动取消选择所选的单选框

时间:2017-10-03 07:29:18

标签: javascript php html

我使用下面的代码从数据库表中获取数据而不刷新页面。在page_one上,我有这段代码:

JAVASCRIPT

function dis()
{
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","page_two.php",false);
    xmlhttp.send(null);
    document.getElementById("get_question").innerHTML=xmlhttp.responseText;
}
dis();
setInterval(function(){
    dis();
},1000);

HTML

<div id="get_question"></div>

PHP

这是在page_two

echo "
<form id='myform1' action='checkbox_no_refresh.php' method='post' >

   <h4>Question No 1</h4>
   <p style='font-size:14px; margin:0px 10px'>$question</p><br>

   A <input type='checkbox' name='checkbox[]' value='A'> $option_a
   B <input type='checkbox' name='checkbox[]' value='B'> $option_b
   C <input type='checkbox' name='checkbox[]' value='C'>$option_c
   D <input type='checkbox' name='checkbox[]' value='D'>$option_d   

  <button id='sub1' name='enter1' class='btn btn-success'>Save</button>
</form>  ";

一旦数据到达数据库,代码就会在不刷新页面的情况下获取数据。但现在的问题是,当我勾选任何复选框时,它会在我在JavaScript中指定的时间后自动取消选择。即在这个例子中是1秒。希望有人能帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

保存状态

var states = Array.prototype.map.call(document.querySelectorAll('input[name="checkbox[]"]'), function(el) {
    return {value: el.value, checked: el.checked};
});

恢复状态

states.forEach(function(x) {
    var value = x.value;
    var checked = x.checked;
    document.querySelector('input[name="checkbox[]"][value=' + value + ']').checked = checked;
})

或者,像老板一样编码

let states = [].map.call(document.querySelectorAll('input[name="checkbox[]"]'), ({value, checked}) => ({value, checked}));

states.forEach(({value, checked}) => document.querySelector(`input[name="checkbox[]"][value=${value}]`).checked = checked);