This is my Javascript code:
const checkbox = document.querySelector("#checkbox");
const button = document.querySelector("#button");
button.addEventListener("click", function(e){
var text = "";
if(checkbox.checked === true){
text = "Is Checked";
}
$.ajax({
url: '/update_if_checked/',
data: {'is_checked': text},
type: 'POST'
}).done(function(response){
console.log(response);
});
});
I am getting an error which says $.ajax is not a function at HTMLButtonElement.
Here, checkbox is an input of type checkbox and when the button whose id is "button" is clicked, I want to send the data i.e. if the checkbox is checked to the Django Server.
I have imported this version of jquery in HTML:
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
EDIT
Sorry about the id of the button that’s button only.
HTML:
<div>Check<input type="checkbox" id="checkbox"></div>
<button id="button">Submit</button>
4
Answers
Your html elements has two similar ids
Change one to checkboxinput and the other to checkboxbutton
Try this maybie:
Simply using your code works fine. Make sure to include jQuery BEFORE your regular JS code. Tried in JSFiddle and do not get any $.ajax() errors besides CORS, of course, because we do not have access to the path (URL for AJAX call).
First of all in your html code, both of the elements i.e. the checkbox and the button have same id. Make it different.
The script part, I have written it using jquery.