The error you're encountering:
Uncaught TypeError: Cannot read properties of undefined (reading 'init') at line 107
is happening because the variable M is undefined in your JavaScript code. The M variable is typically used when working with the Materialize CSS framework, which provides the M object for initializing components like modals and select elements.
Here's how you can fix this issue:
1. Include Materialize CSS and JavaScript Files
Ensure that you have included the Materialize CSS and JavaScript files in your template. These files should be included before your custom script that uses the M object.
In your HTML template, add the following within the <head> section (for CSS) and just before the closing </body> tag (for JavaScript):
<!-- In the <head> section -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet">
<!-- Just before the closing </body> tag -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
2. Correct the JavaScript Initialization Code
There are a couple of typos and issues in your JavaScript code:
- Typo: The variable
instanace is misspelled. It should be instance.
- Redeclaration: You're redeclaring
var elem and var instanace; it's better to use different variable names for clarity.
- Initialization Timing: The initialization of Materialize components should occur after the DOM has fully loaded.
Here's the corrected JavaScript code:
document.addEventListener('DOMContentLoaded', function() {
// Initialize the modal
var modalElems = document.querySelectorAll('.modal');
var modalInstances = M.Modal.init(modalElems);
// Initialize the select element
var selectElems = document.querySelectorAll('select');
var selectInstances = M.FormSelect.init(selectElems);
});
3. Wrap Initialization in DOMContentLoaded Event
Wrapping your initialization code inside document.addEventListener('DOMContentLoaded', function() { ... }); ensures that the DOM is fully loaded before the script runs. This prevents issues where the script tries to initialize elements that aren't yet present in the DOM.
4. Use querySelectorAll for Multiple Elements
If you have multiple modals or select elements, it's good practice to use document.querySelectorAll and initialize them all at once. Even if you have only one instance now, this makes your code scalable.
5. Check Your HTML Structure
Ensure that your modal and select elements are structured correctly according to Materialize's documentation.
Modal Trigger and Structure:
<!-- Trigger Button -->
<button class="btn modal-trigger" data-target="expenseModal">
<i class="fas fa-plus-circle mr-2"></i> Add Expense
</button>
<!-- Modal Structure -->
<div id="expenseModal" class="modal">
<div class="modal-content">
<h4 class="font-weight-bold">Add Expense</h4>
<form action="" method="POST">
{% csrf_token %}
<!-- ... form fields ... -->
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<div class="modal-footer">
<button class="modal-close btn-flat">Close</button>
</div>
</div>
Select Element:
<div class="input-field">
<select id="category" name="category">
{% for category in category_list %}
<option value="{{ category.name }}">{{ category.name }}</option>
{% endfor %}
</select>
<label for="category">Category</label>
</div>
6. Remove Conflicting Bootstrap Classes (If Any)
If you're also using Bootstrap in your project, some classes and JavaScript components may conflict with Materialize. For example, modal-trigger and modal classes are used by both frameworks but function differently.
To resolve conflicts:
- Stick to one framework for UI components to avoid class and JavaScript conflicts.
- If you must use both, namespace your classes to prevent overlap, or use one framework for specific components.
7. Update Modal Trigger Attributes
In Materialize, the modal trigger should have the data-target attribute matching the id of the modal:
<button class="btn modal-trigger" data-target="expenseModal">
Add Expense
</button>
8. Check for Missing jQuery (If Using Older Versions)
Materialize version 1.0.0 and above does not require jQuery. Ensure you're using version 1.0.0 or newer. If you're using an older version, include jQuery before Materialize's JavaScript:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Example of the Corrected Template
Here's how your corrected template might look:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}
<title>Finance List</title>
{% endblock title %}
<!-- Materialize CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet">
</head>
<body>
{% block content %}
<!-- Your content here -->
<!-- ... -->
<!-- Trigger Button for Modal -->
<center>
<button class="btn btn-success btn-large modal-trigger" data-target="expenseModal">
<i class="fas fa-plus-circle mr-2"></i> Add Expense
</button>
</center>
<!-- Modal Structure -->
<div id="expenseModal" class="modal">
<div class="modal-content">
<h4 class="font-weight-bold">Add Expense</h4>
<form action="" method="POST">
{% csrf_token %}
<!-- Form Fields -->
<!-- ... -->
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
<div class="modal-footer">
<button class="modal-close btn-flat">Close</button>
</div>
</div>
<!-- Materialize JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Your Custom Script -->
<script>
document.addEventListener('DOMContentLoaded', function() {
// Initialize Modal
var modalElems = document.querySelectorAll('.modal');
var modalInstances = M.Modal.init(modalElems);
// Initialize Select
var selectElems = document.querySelectorAll('select');
var selectInstances = M.FormSelect.init(selectElems);
});
function deleteExpense(e){
let id = e.dataset.id;
let row = document.getElementById(id);
row.remove();
fetch('',{
method:'DELETE',
headers : {
'X-CSRFToken' : '{{ csrf_token }}',
'Content-Type': 'application/json'
},
body:JSON.stringify({'id' :id}),
credentials : 'same-origin',
});
}
</script>
{% endblock content %}
</body>
</html>
Additional Notes:
- CSRF Token in Fetch Request: Ensure that you're including the CSRF token correctly in your fetch request headers.
- Content-Type Header: Include the
'Content-Type': 'application/json' header in your fetch request if you're sending JSON data.
- Error Handling: Consider adding error handling to your JavaScript code to manage any potential fetch errors.
By making these changes, you should eliminate the Uncaught TypeError and have a functioning modal and select element using Materialize CSS. If you continue to experience issues or have further questions, feel free to ask!