Skip to content
Advertisement

Contained submit button validating other forms

I have two forms on my page, each with its own fields and submit button, but whenever I use any of them, they always check the overall page fields instead of just the form they’re contained in…

The simulator.html has two forms, the first one is this:

JavaScript

And the second one is this:

JavaScript

The views.py file has the back-end code for each, the first one is this:

JavaScript

And the second form back-end script is this:

JavaScript

I thought by specifically calling the mentioned fields and containing them into forms classes, I would avoid an overall validation, but right now I’m failing to make the submit button focus on their own forms. How can I fix this, please?

Advertisement

Answer

You have two forms. One is within the ‘form-1’ div. One is within the ‘form-2’ div. Each one has its own <form> and </form> tags, which means they are separate forms. The first form contains two <input> fields: one called capital_html, one called price_html, and a button called btn. The second form has one <input> field called ticker_symbol_html and a button called btn.

Let’s say the user fills in the first two fields and clicks the first button. That’s going to send a request to whatever the URL is in the <form> tag. In the data, it will send three things:

JavaScript

That’s it. That’s all you get. You don’t get any fields from the other form. If the user clicks the other form, all you will get is

JavaScript

The problem, as you can see, is there’s no easy way for you to tell which form was submitted. If you have to use the same URL for both, the usual way to solve this is to add a hidden field that gets sent with the data, like:

JavaScript

and in the second one:

JavaScript

Now, your handler can say

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement