Created
July 16, 2024 23:28
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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