需要datalist

时间:2016-07-20 17:41:59

标签: php html html-datalist

我希望用户无法提交表单,除非他们从下拉列表中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,但这很容易被忽略。

2 个答案:

答案 0 :(得分:0)

输入标记中使用与您定位的数据列表具有相同ID的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>

如果你希望得到一些帮助,我很乐意提供帮助。

答案 1 :(得分:0)

如果您想进行服务器端验证,

<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!';
}