【问题标题】:HTML form field required if another field is not null如果另一个字段不为空,则需要 HTML 表单字段
【发布时间】:2021-11-16 07:42:08
【问题描述】:

尝试获取需要的“位置”如果“名称”字段不为空。 我不完全理解 java 或 jQuery,所以我一直在看的例子没有意义。对不起,我是个菜鸟,但我一直在谷歌搜索,只是没有看到解决方案。

<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>

【问题讨论】:

  • 你想用 PHP 做到这一点吗?你试过什么?你检查过这个吗:stackoverflow.com/questions/5627747/…
  • 我想在客户端做,所以我猜是 Java 或 jQuery。
  • 您将其标记为php...您尝试过吗? stackoverflow.com/questions/33294368/…
  • Java 和 Javascript 是两个非常不同的东西。它们是编程语言,名称中都包含 Java 一词。这几乎是关系结束的地方。不要混淆 2。

标签: javascript php html


【解决方案1】:

尝试使用以下内容。它使得每当“名称”输入更新时,它都会检查它是否具有值。如果是,它会将“位置”输入更新为要求。

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>

看看这是否有助于您尝试做的事情。

【讨论】:

    【解决方案2】:

    您的表单中有两个字段。名称字段是必需的。位置不。意味着如果位置为“null”,您将无法发送表单。如果位置有一个值,那么您可以为名称选择设置一个必需的参数,以避免在没有这两个字段的情况下发送表单。

    &lt;select name="location" id="location" required&gt;

    【讨论】:

      【解决方案3】:

      您需要在客户端使用 javascript 执行此操作,并在服务器端使用 php 验证提交的数据。

      首先,如果您希望允许用户不选择位置(无论出于何种原因),您的 &lt;select&gt; 标记应包含带有空值的 &lt;option&gt;。

      试试这个代码:

      <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> 
      

      然后使用 javascript 尝试将 eventlistener 添加到 name 输入,如果值不为 null,则将位置更改为必需。

      试试这个代码:

      // 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;
          }
      });
      

      现在您需要使用PHP 验证提交的数据

      试试这样的:

      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";
          }
      }
      

      以上代码只是一个示例,向您展示如何验证提交的数据。

      【讨论】:

        【解决方案4】:

        您可以使用 Javascript 将 disbaled 属性添加到您希望需要的每个条目的 HTML 中。然后使用事件侦听器检查每个所需条目的验证。

        您希望名称是必需的,因此禁用选择和提交按钮。使用模糊事件检查名称输入字段,这意味着元素已失去焦点。如果name.value 为空,则一旦事件触发,然后禁用下一个字段,即您的选择。正确填写 name 后,我们将 disabled 属性属性设置为 false 然后我们使用 change 事件检查 selects 元素。当它发生变化时,如果它没有设置为默认设置,其值为空 "",那么我们将提交按钮 disabled 属性设置为 true 改为 假。

        注意:我已将 ID 添加到您的每个表单字段中,以使用该 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>

        【讨论】:

          【解决方案5】:

          使用数据属性来定义您的关系,世界就是您的牡蛎。以下只是一个起点,但会为您提供所需的内容。在该示例中,当检查“其他”复选框时,根据需要标记两个字段。

          在data属性中定义依赖,你可以使用任何有效的CSS Selector来选择依赖的元素。

          /*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>

          但实际上,“名称”字段是必需的,因此逻辑上默认情况下也应该需要位置字段

          【讨论】:

            猜你喜欢
            • 2022-01-17
            • 2017-06-07
            • 1970-01-01
            • 2020-12-23
            • 2021-12-10
            • 2016-12-18
            • 2021-10-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多