I want to make a dynamic page, but when I make a request the page just refreshes, although it should return an alert when no data is entered (I have not entered any).
views.py
def adding(request):
return render(request, 'matrix_app/adding_matrix.html')
create_matrix.js
function create_matrix(){
let rows1 = document.getElementById("rows_1_matrix").textContent;
let columns1 = document.getElementById("columns_1_matrix").textContent;
let rows2 = document.getElementById("rows_2_matrix").textContent;
let columns2 = document.getElementById("columns_2_matrix").textContent;
nums = [rows1, rows2, columns1, columns2];
for(let i = 0; i < 4; i++){
if (nums[i] === false || nums[i] === '0') {
return alert("All fields are ruqired");
}
}
}
adding_matrix.html
% extends 'base.html' %}
{% load static %}
{% block content %}
<script src="{% static 'js/create_matrix.js' %}"></script>
<form onsubmit="create_matrix()" id="matrix" method="post">
{% csrf_token %}
<div>
<label>text</label>
<input type="number" id="rows_1_matrix"/>
</div>
<div>
<label>text</label>
<input type="number" id="columns_1_matrix"/>
</div>
<div>
<label>text</label>
<input type="number" id="rows_2_matrix" />
</div>
<div>
<label>text</label>
<input type="number" id="columns_2_matrix"/>
</div>
<input type="submit" value="generate"/>
</form>
<a href="/operations"><button>Back</button></a>
{% endblock %}
2
Answers
Refreshing the page is the default behaviour for a submit type action. You have to prevent this default behaviour using
e.preventDefault()
. Your code will look like:-create_matrix.js
adding_matrix.html
I think there is unclear point about what you want to do. I understood that you want to create matrix means putting random values in input number HTML DOM. Therefore you do not need to submit the form to server. If you submit your form to the server, it hands your request and responds to the same HTML file again. As a result, you always have a original empty form in HTML.
Solution: Please; define your input element to run create_matrix method in below:
Then change your method to validate input number value as if it is empty or null or NaN.
create_matrix runs as a validator for your input. If you send input values to the server after validating you can use ajax with jquery or with pure js. Balraj Singh was right. You have to prevent your default form submit action. Therefore we can change our create_matrix method as submit data after validating the inputs. You can check ajax from here https://www.w3schools.com/xml/ajax_intro.asp.
views.py
create_matrix.js