简体   繁体   English

如果另一个字段不为空,则需要 HTML 表单字段

[英]HTML form field required if another field is not null

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.我不完全理解 java 或 jQuery,所以我一直在看的例子没有意义。 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>

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">BC</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.看看这是否有助于您尝试做的事情。

You can add the disbaled attribute using Javascript to the HTML for each entry you wish to be required.您可以使用 Javascript 将 disbaled 属性添加到您希望需要的每个条目的 HTML 中。 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 .如果name.value为空,则事件触发后,请禁用下一个字段,即您的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.正确填写名称后,我们将禁用属性属性设置为false ,然后我们使用更改事件检查选择元素。 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 .当它发生变化时,如果它没有设置为默认设置,它的值没有""然后我们将提交按钮禁用属性从true 设置false

Note: I have added Ids to each of your form fields to query each element using that ID.注意:我已将 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">BC</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>

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>

You need to do it on client side with javascript and validate the submitted data on server side with php.您需要使用 javascript 在客户端执行此操作,并使用 php 在服务器端验证提交的数据。

First your <select> tag should contain <option> with empty value if you want to allow user not to select location (For whatever reason).首先,如果您想让用户不选择位置(无论出于何种原因),您的<select>标签应该包含带有空值的<option>

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.然后使用 javascript 尝试将 eventlistener 添加到name输入,如果该值不为空,则将位置更改为必需。

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现在您需要使用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.上面的代码只是一个例子,向您展示如何验证提交的数据。

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 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.在定义依赖的 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, function(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">BC</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但实际上,您已将“名称”字段表示为必需,因此从逻辑上讲,默认情况下也应需要位置字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM