Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 传递给Django视图的选中和未选中复选框的值_Html_Django_Ajax - Fatal编程技术网

Html 传递给Django视图的选中和未选中复选框的值

Html 传递给Django视图的选中和未选中复选框的值,html,django,ajax,Html,Django,Ajax,我有一个复选框,我希望它在选中/取消选中时返回不同的值 <form id="cat">{% csrf_token %} <input type="checkbox" id="chk" value="1" unchecked> </form> <script type="text/javascript"> $(document).on('submit','#cat',function(e){ e.preventDefault();

我有一个复选框,我希望它在选中/取消选中时返回不同的值

<form id="cat">{% csrf_token %} 
<input type="checkbox" id="chk" value="1" unchecked> 
</form>
<script type="text/javascript">
$(document).on('submit','#cat',function(e){
    e.preventDefault();
    $.ajax({
        type:'POST',
        url:'/cat',
        data:{
            chk:$('#chk').val(), 
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },

我想在选中/未选中复选框的情况下,使用不同的值分配
chked

我指的是,我认为如果检查与否,值会有所不同

但是,无论是否选中,都返回相同的值1

我在这里遗漏了什么,或者有更好的方法吗?谢谢。

val()函数返回元素“1”的值。您不能使用它来检查复选框的状态。您可以使用checked属性,例如:

$('#chk').checked
根据是否选中复选框,返回
true
false
。你可以在网上阅读更多

$('#chk').checked