Reputation: 179
I have a checkbox that I would like it to return different values when check/unchecked.
<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()
},
In the cat
function in views.py
, I have
chked=request.POST.get('chk', '')
I want to assign chked
with different values with the checkbox checked/unchecked.
I was referring to https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox and thought that value would be different if checked or not.
However, same value of 1 returned whether checked or not.
What am I missing here or is there a better way to do this? Thanks.
Upvotes: 0
Views: 651
Reputation: 2212
The val() function returns the value of the element which is '1'. You cannot use it to check the state of a checkbox. What you could do is to use the checked attribute, e.g.:
$('#chk').checked
which returns true
or false
depending on whether the checbox is checked or not. You can read more in the jQuery doc.
Upvotes: 1