0

Trying to get the "location" to be required if the "name" field is not null. I don't completely understand java or jQuery so the examples I've been looking at don't make sense. Sorry for being a noob but I've been googling for and just not seeing the solution.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Name: <input type="text" name="name" required>
    <label for="location">Choose a location:</label>
    <select name="location" id="location">
      <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>
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Are you trying to do that with PHP? what have you tried? Have you check this: https://stackoverflow.com/questions/5627747/validating-select-box-with-php – A. Meshu Nov 15 '21 at 22:02
  • I would like to do it on the client side so I'm guessing Java or jQuery. – David McKittrick Nov 15 '21 at 22:06
  • You tagged it as `php`... Have you tried this? https://stackoverflow.com/questions/33294368/select-option-required-on-submit-using-javascript – A. Meshu Nov 15 '21 at 22:09
  • Java and Javascript are two very different things. They are programming languages both containing the word Java in the name. That is pretty much where the relationship ends. Don't get the 2 confused. – Jon P Nov 15 '21 at 23:28

5 Answers5

2

try using the following. It makes it so whenever the "name" input is updated it will check to see if it has a value. If it does, it will update the "location" input to require.

function updateRequirements() {
  var name = document.getElementById('name').value;
  if (name != null) {
    document.getElementById('location').required = true;
  } else {
    document.getElementById('location').required = false;
  }
}
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Name: <input type="text" id="name" name="name" onchange="updateRequirements();">
        <label for="location">Choose a location:</label>
        <select name="location" id="location">
          <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>

See if this helps for what you're trying to do.

0

You can add the disbaled attribute using Javascript to the HTML for each entry you wish to be required. Then check the validation of each required entry with an event listener.

You want the name to be required, so disable both the select and submit buttons. Check the name input field using a blur event, which means the element has lost focus. Once the event fires if the name.value is empty, then disable the next field, which is your select. Once the name is properly filled out, we set the disabled attribute property to false and then we check the selects element using a change event. When it has changed, provided it is not set to the default setting which has a value of nothing "" then we set the submit buttons disabled attribute from true to false.

Note: I have added Ids to each of your form fields to query each element using that ID.

// query each relavent selector and assign a variable
let loc = document.querySelector('#location');
let submit = document.querySelector('#submit');
let name = document.querySelector('#name');
// disable the next required fields so the user can not move on until 
// they fill out the prior field properly
submit.disabled = true;
loc.disabled = true;

// blur event handler to check the focus out fo the input field
// for example when the user clicks out or hits tab
name.addEventListener('blur', e => {
  // ternary conditional statement to check the value of the name field
  name.value !== '' ? loc.disabled = false : submit.disabled = true
})

// change event handler to check the selects value on change
loc.addEventListener('change', e => {
  // if conditional statement to check the value of the location select
  // makes sure the value is not set to "" which is the default value for 
  // "Select A Location" also double check our name in case user removes after 
  // selecting a location
 loc.value !== '' && name.value !== '' ? 
    submit.disabled = false :
    submit.disabled = true
})
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
  Name: <input type="text" id="name" name="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><span id="error"></span><br>
  <input id="submit" class="unselectable" type="submit" name="submit" value="Submit">
</form>
dale landry
  • 7,831
  • 2
  • 16
  • 28
0

You have two fields in your form. The name field is required. the location not. means that you cant send the form if location is "null". And if the location has a value then you can set a required parameter to name selection to avoid that the form is sending without this two fields.

<select name="location" id="location" required>

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0

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.

جدو على
  • 161
  • 1
  • 8
0

Use data attributes to define your relationships and the world is your oyster. The below is just a starting point but will get you what you need. In that example, two more fields are flagged as required when the "Other" checkbox is checked.

In the data attribute to define the dependencies, you can use any valid CSS Selector to select the dependent elements.

/*Get fields with dependencies*/
let fieldsWithDependencies = document.querySelectorAll("[data-dependantfieldselecor]");

for (var i = 0; i < fieldsWithDependencies.length; i++) {
  /*Add an appropriate event listener based on type*/
  let eventType = fieldsWithDependencies[i].type == "text" ? "input" : "click";
  fieldsWithDependencies[i].addEventListener(eventType, updateDependencies);
  //Add the same for blur, just to be sure
  fieldsWithDependencies[i].addEventListener("blur", updateDependencies);
}

function updateDependencies(event) {
  /*The dependent fields base on the dependent field attribute selector*/
  let dependentFields = document.querySelectorAll(this.dataset.dependantfieldselecor);
  /*Update required based on the element from where the event originated*/
  for (var j = 0; j < dependentFields.length; j++) {
    if (this.type == "checkbox") {
      dependentFields[j].required = this.checked
    } else {
      dependentFields[j].required = this.value.trim().length > 0;
    }
  }
}
<form method="post" action="">
  Name: <input type="text" name="name" required data-dependantfieldselecor="#location">
  <label for="location">Choose a location:</label>
  <select name="location" id="location">
    <option value="ON">Ontario</option>
    <option value="BC">B.C.</option>
    <option value="AB">Alberta</option>
    <option value="MI">Michigan</option>
  </select>
  <br>
  <label for="other">Other</label><input type="checkbox" id="other" data-dependantfieldselecor="#age,.bob">
  <br>
  <label for="age">Age</label><input type="number" id="age">
  <br>
  <label for="something">Something</label><input type="text" id="something" class="bob">
  <br><br>
  <input type="submit" name="submit" value="Submit">
</form>

In reality, though, you have the "name" field indicated as required, so logically the location field should also be required by default

Jon P
  • 19,442
  • 8
  • 49
  • 72