I have a checkbox it’s change text when checked (check is text = on, uncheck is text = off and this value are 0 and 1) I want get value 0 or 1 (check get 1 uncheck get 0) by ajax but I confuse in my code
$("#onoff").click(function() {
if ($(this).is(':checked')) {
$("#hidden_onoff").text("ON");
} else {
$("#hidden_onoff").text("OFF");
}
});
$('#onoff').change(function() {
if ($(this).prop('checked')) {
$('#hidden_onoff').val('1');
} else {
$('#hidden_onoff').val('0');
}
});
$.ajax({
url: "/on_off",
method: "POST",
data: {
onoff: $("#hidden_onoff").val(),
},
success: function(data) {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="on_off">
<div class="container">
<div class="form-check form-check-inline">
<input id="onoff" type="checkbox" checked="checked" />
<label class="checkbox-inline" id="hidden_onoff">ON</label>
</div>
</div>
</form>
3
Answers
1st: ID must be unique don’t use same id for more than one element
2nd:
$("#hidden_onoff")
is alabel
so it has a.text()
not.val()
3rd: You can use one element event to trigger another element event it will be easier to work with
Take a look at this sample code .. Changing ids to form_onoff and text_onoff
You’re setting the
value
of<label id="hidden_onoff">
rather than<input id="onoff">
:However, since you’re using AJAX, it doesn’t seem that you need to change the input’s value anyway. You can define a variable based on whether the input is checked, and send that variable’s value to the server.
Also, it doesn’t seem that you need both
click
andchange
handlers. You can use thechange
event alone. If your intent is to change the input when its text is clicked, I suggest wrapping both the input and text elements in a<label>
.Finally, it looks like you’re executing the AJAX upon page load rather than upon input change. I recommend executing the AJAX from inside your event handler.
Here’s a demonstration:
you need to do a loop for all the input of type check