使数据列表成为必需的

Make datalist required

我希望用户无法提交表单,除非他们从下拉列表中选择了某些内容 datalist,该内容在他们键入时出现。如果他们只是随便输入一些东西,我希望提交表单。

如果这不可能,更好的选择是在用户提交时检查键入的文本是否出现在数据列表中吗?

<form method="post">
    <input type="text" list="browsers">
    <datalist id="browsers">
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
    </datalist>
    <input type="submit" name="submit">
</form>

<?php 
if(isset($_POST['submit']
   // function to check if something from the datalist was clicked and NOT just typed
}else{
   echo'Select something from the datalist!';
}

虽然我可以根据需要设置 datalist,但这很容易被绕过。

在与您定位的数据列表具有相同 ID 的 input 标签中使用 required 将检查强制用户输入内容。

<form method="post">
    <input type="text" list="browsers" required>
    <datalist id="browsers">
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
    </datalist>
    <input type="submit" name="submit">
</form>

<?php 
if(isset($_POST['submit']
   // function to check if something from the datalist was clicked and NOT just typed
}else{
   echo'Select something from the datalist!';
}

但是,它不会阻止用户提供未在下拉列表中列出的输入。这需要在提交前通过 Javascript 检查。

<form method="post" onsubmit="return myCheckFunction(this)>

  <!-- Your form items -->
  <!--------------------->

</form>

<script>
  myCheckFunction(form) {
    // get the values that are currently under the datalist tag in option tags
    // get the user input
    // compare the options with the user input
    // if one is equal with the user input submit the form with the method submit();
    // else don't submit the form, the user will have to change his input
  }
</script>

如果您希望在 js 方面得到一些帮助,我很乐意提供帮助。

如果您想使用服务器端验证,

<form method="post">
    <input type="text" list="browsers" name="items" required>
    <datalist id="browsers" >
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
    </datalist>
    <input type="submit" name="submit">
</form>

<?php 
if(isset($_POST['submit']
   $check = array('Internet Explorer', 'Firefox', 'Chrome', 'Opera', 'Safari');

if(in_array($_POST['items'], $check)){
  // Code to be execute. 
} else{
   echo'Select something from the datalist!';
}

}else{
   echo'Select something from the datalist!';
}