All of the examples of making drop-down forms that I can find involve having a separate PHP file. I'm trying to embed some code into a Weebly page, so I'm not sure that I can save a separate PHP file on the server. So is it possible to avoid PHP entirely? Maybe do everything in JavaScript and jQuery? Or to put the form and the PHP in the same HTML file?
More specifically what I'm trying to do is make a page where there are several drop-down forms. The user selects several options, clicks submit, the client-side back-end does some computation on the inputs, and prints out a result.
I've been trying to follow this guide for dropdowns: https://www.w3schools.com/tags/tag_select.asp
And I've been following this for using PHP in forms: https://www.ntchosting.com/encyclopedia/scripting-and-programming/php/php-in/
With that guidance I created this non-working code:
<!DOCTYPE html>
<?php
$Level = $_POST["level"];
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="post">
Choose a level: <select name="level" id="level">
<option value="high">High</option>
<option value="med">Medium</option>
<option value="low">Low</option>
</select>
</form>
<p>
<?php
echo "".$Level;
?>
</p>
</body>
</html>
I say that it's not working because when I click on anything in the drop-down, nothing happens.
This further information came from an exchange in the comments:
Ah, this really doesn't need to interact with the server. It's ultimately just going to be a tool so that customers can get an automatically generated estimated quote on a price. So they answer some questions (i.e. select some drop-downs and enter some numbers in fields) and click submit, and the web page spits out an estimate. No information saved or anything like that, so it should be fine to handle everything client-side. From your description, though, it sounds like that can't be done with PHP then. I don't think Weebly will let me change the file extension.
You certainly can. You can use the onSubmit
attribute on your form to run some javascript (and by extension jquery) without actually submitting the form. More specifically, it would look something like this:
<form onSubmit="return yourJavascriptFunction()" method="post">
Inside your script, you can get the dropdown values from the form's fields using document.getElementById(yourDropdownID)
and perform any necessary actions. If you don't want your form to redirect, just return false;
on your function. Using this method, you don't really need a form, and can use some <select>
tags with id, as well as a pseudo submit button:
<button onclick="yourFunction()">Submit</button>