You need to do it on client side with javascript and validate the submitted data on server side with php.
First your <select>
tag should contain <option>
with empty value if you want to allow user not to select location (For whatever reason).
Try this code:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" id="name" required>
<label for="location">Choose a location:</label>
<select name="location" id="location">
<option value="">Select a location</option>
<option value="ON">Ontario</option>
<option value="BC">B.C.</option>
<option value="AB">Alberta</option>
<option value="MI">Michigan</option>
</select>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Then with javascript try to add eventlistener to name
input and if the value is not null, change location to required.
Try this code:
// Listen for input and change the select required attribute
document.querySelector('#name').addEventListener('input', function(e) {
const location = document.querySelector('#location');
if (e.target.value.length > 0) {
location.required = true;
} else {
location.required = false;
}
});
Now you need to validate submitted data with PHP
Try something like that:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // if form was submitted
$name = $_POST['name'] ?? "";
$location = $_POST['location'] ?? "";
if ($name && !$location) { // if name is not empty and location is empty
echo "Please enter a location";
} elseif ($name && $location) { // if name and location are not empty
echo "Welcome, $name from $location";
} elseif (!$name && $location) { // if name is empty and location is not empty
echo "Please enter your name";
} else { // if name and location are empty
echo "Please enter your name and location";
}
}
The above code is just an example to show you how to validate submitted data.