Home > Blockchain >  HTML form field required if another field is not null
HTML form field required if another field is not null

Time:11-16

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>

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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>

CodePudding user response:

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.

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related