Skip to content
Advertisement

Change Form Elements Depending On Selected Option

I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let’s say I wanted to make an uploader script, the dropdown box might hold:

Upload
Delete

And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.

I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.

Advertisement

Answer

You can’t do what you want in purely server-side code without some sort of submission from the browser to trigger the check. PHP code runs on the server and returns the page to the browser. Once the page has left the server there’s nothing PHP can do to it.

Sites I’ve seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action. That’s really all you can do without some kind of javascript on the client side.

If you can use javascript then you have many more options:

  1. Trigger a reload of the form when the drop-down box is changed.
  2. Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
  3. Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.

Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application. The server doesn’t need to know about Javascript, or even JQuery. The server runs your PHP code to build the HTML for your page. The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser. Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended. There is no Javascript code in your server-side application. The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.

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