如何使用javascript自动提交已保存/重新填充的复选框

时间:2015-02-25 00:25:40

标签: javascript

有人可以告诉我如何在页面重新加载时自动提交我保存/重新填充的复选框选项吗?一旦重定向到页面然后再返回,复选框就会正确重新填充,但我不确定如何自动提交结果。

形式

<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" id="1" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> $2000 And Under<br>

<input type="checkbox" name="2kto4k" class="checkbox" id="2" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> $2001 To $4000<br>
</script>    
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> $4001 And Up<br></td>

选中框时自动提交的javascript。我尝试将此代码实现到下面的javascript我用来重新填充选中的复选框但无法使其工作。

<script type="text/javascript">  
$(function(){
 $('.checkbox').on('change',function(){
    $('#form').submit();
    });
});

javascript我用来在用户点击“收藏夹”按钮后重新填充复选框,然后将其转到php脚本,然后重定向回此页面。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>

<script>
  $(":checkbox").on("change", function(){
    var checkboxValues = {};
    $(":checkbox").each(function(){
      checkboxValues[this.id] = this.checked;
    });
    $.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
  });

  function repopulateCheckboxes(){
    var checkboxValues = $.cookie('checkboxValues');
    if(checkboxValues){
      Object.keys(checkboxValues).forEach(function(element) {
        var checked = checkboxValues[element];
        $("#" + element).prop('checked', checked);
      });
    }
  }

  $.cookie.json = true;
  repopulateCheckboxes();



</script>

PHP

if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
 $arguments[] = "`2kto4k` = 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup = 'yes'";
}
if(!empty($arguments)) {
$str = implode(' AND ',$arguments);

$qry = "SELECT favorite_id, id, venue, imageurl FROM venue_ads WHERE `showingads` = 'yes' AND " . $str . "";


$result = $conn->query($qry);



 if ($result->num_rows > 0)

复选框正确重新填充,但不提交任何内容。如何重新填充javascript提交重新填充的复选框?

1 个答案:

答案 0 :(得分:0)

我可能会误读您的问题,因为您似乎可以通过表单提交跟随您对repopulateCheckboxes()的调用,如下所示:

repopulateCheckboxes();
document.getElementById('form').submit();

也许你可以抛出一个jsbin的例子?

相关问题