I have a webpage with a button. clicking the button opens a modal. inside this modal there’s a (Django) form. it has few inputs and some buttons (including a submit
button).
- my form is:
<form method="post" id="backupCreateForm" action="/backup/create/"> ...</form>
- its parent, the modal is :
<div class="modal fade in" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
I can’t seem to select the submit button within the form element with document.getElementById
, it returns undefined
. how can I select it?
<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" xit
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="createModalLabel">Create Form</h5>
</div>
<div class="modal-body">
<form method="post" id="backupCreateForm" action="{% url 'backup_create' %}">
</form>
</div>
</div>
</div>
</div>
backupCreateForm:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success" id="submitButton">Create</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</form>
my final goal is to add some extra functionality to the button (an api call) alongside actually submitting the form (I want to keep it in the template, and not in Django views/models)
P.S one idea is to programmatically submit the form with something like:
document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('myform');
form.addEventListener('submit', function(event) {
event.preventDefault();
submitForm();
});
});
function submitForm() {
const form = document.getElementById('myform');
const formData = new FormData(form);
fetch('{% url "form_submit" %}', {
method: 'POST',
body: formData,
headers: {
'X-CSRFToken': '{{ csrf_token }}'
}
})
.then(response => response.json())
.then(data => {
// Handle the response from the server
console.log(data);
if (data.success) {
// Call the API
callAPI();
} else {
// Handle form errors
console.error(data.errors);
}
})
.catch(error => {
// Handle any errors
console.error(error);
});
}
function callAPI() {
fetch('/api/endpoint/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Handle the API response
console.log(data);
})
.catch(error => {
// Handle any errors
console.error(error);
});
}
but how can I do the same thing without writing the form submission manually?