|
6 | 6 | </form>
|
7 | 7 | </div>
|
8 | 8 |
|
9 |
| - <table class="form-container"> |
| 9 | + <table class="form-container" id="categories-form-container"> |
10 | 10 | <thead>
|
11 | 11 | <tr>
|
12 | 12 | <th>User</th>
|
|
29 | 29 | </form>
|
30 | 30 | </div>
|
31 | 31 | {{/categories}}
|
32 |
| - <form method="POST" action="" class="add-category-form"> |
33 |
| - <input type="text" name="category" placeholder="New Category" required> |
| 32 | + <form method="POST" class="add-category-form"> |
| 33 | + <input type="text" name="category" placeholder="New Category" id="{{username}}category" required> |
34 | 34 | <input type="hidden" name="username" value="{{username}}">
|
35 |
| - <button class="add-button" type="submit" name="action" value="add">Add</button> |
| 35 | + <input type="hidden" name="action" value="add"> |
| 36 | + <button class="add-button" value="add" onclick="addCategory( event => event)"> |
| 37 | + Add |
| 38 | + </button> |
36 | 39 | </form>
|
37 | 40 | </td>
|
38 | 41 | </tr>
|
|
41 | 44 | </table>
|
42 | 45 | </div>
|
43 | 46 | <script>
|
44 |
| - if( window.history.replaceState ) { |
45 |
| - window.history.replaceState( null, null, window.location.href ); |
| 47 | + window.history.replaceState?.( null, null, window.location.href ); |
| 48 | +
|
| 49 | + function addCategory( event ) { |
| 50 | + event.preventDefault(); |
| 51 | + const form = event.target; |
| 52 | +
|
| 53 | + if( !form.checkValidity() ) { |
| 54 | + return form.reportValidity(); |
| 55 | + } |
| 56 | +
|
| 57 | + fetch( window.location.href, { method: 'POST', body: new FormData( form ) } ) |
| 58 | + .then( response => response.text() ) |
| 59 | + .then( html => { |
| 60 | + const newDoc = new DOMParser().parseFromString( html, 'text/html' ); |
| 61 | + const container = document.querySelector( "#categories-form-container" ); |
| 62 | + const newContainer = newDoc.querySelector( "#categories-form-container" ); |
| 63 | +
|
| 64 | + container.replaceWith( newContainer ); |
| 65 | +
|
| 66 | + const username = form.elements.username.value; |
| 67 | + const inputField = document.getElementById( `${ username }category` ); |
| 68 | + inputField?.focus(); |
| 69 | + } ) |
| 70 | + .catch( error => console.error( 'Error:', error ) ); |
46 | 71 | }
|
47 | 72 | </script>
|
0 commit comments