Skip to content

Instantly share code, notes, and snippets.

@archatas
Created July 16, 2024 23:28
Show Gist options
  • Save archatas/6993cabd19d5325889355191701eed2e to your computer and use it in GitHub Desktop.
Save archatas/6993cabd19d5325889355191701eed2e to your computer and use it in GitHub Desktop.
Implementation of a field reset based on a default value from a URL path
<div class="form-field">
<label for="title">Title</label>
<input type="text" id="title" />
<button type="button"
class="reset_field"
data-url="http://example.com/default-title/"
data-target="#title"
>Reset title</button>
</div>
<div class="form-field">
<label for="title">Description</label>
<textarea id="description"></textarea>
<button type="button"
class="reset_field"
data-url="http://example.com/default-description/"
data-target="#description"
>Reset description</button>
</div>
<script src="reset_field.js"></script>
document.addEventListener('DOMContentLoaded', function() {
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
const resetFields = document.querySelectorAll('.reset_field');
resetFields.forEach(function(field) {
field.addEventListener('click', function() {
const url = this.dataset.url;
const targetSelector = this.dataset.target;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'X-CSRFToken': csrftoken
},
credentials: 'same-origin', // This ensures cookies are sent with the request
})
.then(response => response.text())
.then(data => {
const targetElement = document.querySelector(targetSelector);
if (targetElement) {
targetElement.value = data;
}
})
.catch(error => console.error('Error:', error));
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment