在不刷新页面的情况下获取复选框值 [英] Get checkbox value without page refresh

查看:88
本文介绍了在不刷新页面的情况下获取复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框表:

<td><input id="box" name="box" type="checkbox" value="1" checked /></td>
<td><input id="box" name="box" type="checkbox" value="2" checked /></td>
<td><input id="box" name="box" type="checkbox" value="3" checked /></td>

我想在选中或取消选中复选框时一次提交复选框值(一次选中一个复选框).无需刷新该页面即可:

I want to submit checkbox value when I check or uncheck the box (each one at a time) Without refreshing the page to:

if (isset($_GET['box'])) {
   echo "Success!"
}

到目前为止,我已经获得了以下javascript代码来检查该框是否处于选中状态:

By far I got this javascript code to check whether the box is checked or unchecked:

function validate(){ 
if (document.getElementById('box').checked){
    alert("checked") ;
}else{
    alert("You didn't check it! Let me check it for you.")
}
}

我想在上面添加AJAX,但是到目前为止,我尝试的所有代码段都与我的代码不匹配.感谢您的帮助.

I want to add AJAX on it, but all the snippet code I try so far didn't fit good with my code. I'll thank for your help.

推荐答案

您要使用AJAX.这是一个没有AJAX的jQuery示例:

You want to use AJAX. Here is an example in jQuery without AJAX:

<td><input id="box1" class="box" name="box1" type="checkbox" value="1" checked /></td>
<td><input id="box2" class="box" name="box2" type="checkbox" value="2" checked /></td>
<td><input id="box3" class="box" name="box3" type="checkbox" value="3" checked /></td>

JavaScript:

JavaScript:

$(document).ready(function() {
  $('.box').on('change', function(event) {
    var checkbox = $(event.target);
    var isChecked = $(checkbox).is(':checked');
    alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
  });
});

演示: http://jsbin.com/ipasud/1/

现在而不是执行alert调用,而是将$ .post传递到一个后端URL,该URL带有一个id和一个值为checked或unchecked的值.例如,

Now instead of doing an alert call, do a $.post to a backend URL that takes an id and a value of checked or unchecked. For example,

$.post('/submit-checkbox.php', {id: checkbox.attr('id'), value: isChecked});

如果我们将其放回代码中,它将看起来像这样:

And if we put that back into the code, it would look like this:

$(document).ready(function() {
  $('.box').on('change', function(event) {
    var checkbox = $(event.target);
    var isChecked = $(checkbox).is(':checked');
    $.post('/whatever-your-url-is.php', {id: checkbox.attr('id'), value: isChecked});
  });
});

这篇关于在不刷新页面的情况下获取复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆