I am trying to ensure that part II of the HTML page is executed only after I have successfully submitted the required information through the form.
This problem is part of a Flask application. I am trying to run Part II only after Part I, because otherwise I would have a python stream webcan function running automatically.
<!--Part I -->
<form id="form" action="{{ url_for("index")}}" method="post">
<div >
<div >
<label for="txtName">Name:</label>
<input name="host" id="txtName" />
</div>
<div >
<label for="txtAge">Age:</label>
<input name="port" id="txtAge" />
</div>
</div>
</form>
<!--Part II -->
<div >
<div >
<img src="{{ url_for('video_feed') }}">
</div>
</div>
How do I create an if condition inside an HTML page that becomes true when the button is clicked?
CodePudding user response:
It depends on what the business logic should be and if it should be on backend or frontend.
Based on your question, I assume the following: You have a form (part 1) and you want to display the rest of your code (part 2) only when the form has been submitted with the required data. If so, this may help:
document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
if (document.getElementById('txtName').value.length > 0 && document.getElementById('txtAge').value.length > 0) {
document.querySelector('.container').removeAttribute('hidden');
}
});
<!--Part I -->
<form id="form" action='{{ url_for("index")}}' method="post">
<div >
<div >
<label for="txtName">Name:</label>
<input name="host" id="txtName" />
</div>
<div >
<label for="txtAge">Age:</label>
<input name="port" id="txtAge" />
</div>
</div>
<button type="submit">Submit</button>
</form>
<!--Part II -->
<div hidden>
<div >
<img src="{{ url_for('video_feed') }}">
</div>
</div>
This checks whether the input fields contain values. Since this is only for the frontend, you will have security issues if you do not validate the data in the backend as well.
You also have security issues if you place your "secret" code directly in DOM, even if it is hidden. If it is secret, you should retrieve the data from your server whenever it is needed.
CodePudding user response:
I recommend using Django to integrate your python code seamlessly with HTML forms.
You can achieve this using HTML Javascript, here's an example:
<button onclick="submitForm()">Submit</button>
<div id="myDIV">
This is my DIV element.
</div>
Javascript:
function submitForm() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}