As a Magento 2 Store owner, you always need to collect various information from your potential customers using the form to provide quality service. In the 21st Century along with people, forms are getting smarter by using dependencies on various user inputs which helps to save tons of time and reduce efforts to fill online forms. This ultimately leads to the success rate of forms.

With dynamic dependent form fields, Store owner can easily ask further qualifying questions based on the user’s answers using various conditions. Basically, dependent forms dynamically show/hide or changes the value of form fields based on the user selections.
For example, if you want to list out products of a particular category, then we have to create category-products dropdown so that when users select a category, related products will be shown in dropdown option.

Here we’ve come up with the custom code in which whenever customer picks any option from drop-down another dropdown should be displayed with respective options based on the dropdown 1 selection. We have developed this functionality using Ajax code, which today we are likely to share with you guys on our blog.

Firstly, you need to add form to your phtml file with following code.

Once you have added the code to your file, you need to create block file “Index.php” at app\code\Vendor\Extension\Block\

Lastly, we need to create action using “ajax-handler.php” file that can handle all the ajax request comes from frontend form.
app\code\Vendor\Extension\Controller\Extension\

And Tadaa, you are done with adding dependent dropdown options in your Magento 2 store frontend form. You can even add or change form elements based on your requirement of collecting various information.
Feel free to ask any question regarding this code, I would be glad to help you.
Let us know in comment section that how you have used this code and don’t forget to smash below stars.

Happy Coding!

Click to rate this post!
[Total: 6 Average: 4.3]