javascript - 如何避免提交不在建议数据列表中的文本

标签 javascript php html

问题是我不希望用户输入数据列表不建议的搜索字符串。例如,我的数据列表建议用户使用以下内容:

Nahid's Kichen

Italian Dishes

ABC Restaurant

在这种情况下,用户可以输入这三个选项以外的值,例如

Chinese

我不希望用户能够输入他想要的内容,我希望用户必须在建议的 3 个选项之间进行选择。

如需澄清,请敲我,谢谢

摘要代码如下:

<input type="text" name="search" list="categoryname" autocomplete="off" id="pcategory" style="width:200px;height:40px; border:1px thick;font-weight:bold" placeholder="Location or Restaurant" required/>
 <datalist id="categoryname">
    <?php while($row = $qry->fetch_assoc()) { ?>
        <option   value="<?php echo  $row['acc_id']."=".$row['res_name']." , ".$row['res_city'];?>"><?php echo $row['res_name']." , ".$row['res_city']." , ".$row['res_country']; ?></option>
    <?php } ?>
</datalist>

最佳答案

您可以在单击搜索按钮时运行自定义验证函数,以确保搜索值与餐厅列表中的可用值之一相对应。

工作示例:

// Create list of valid restaurant names
var restaurants = document.getElementsByTagName('option');
var restaurantList = [];

for (var i = 0; i < restaurants.length; i++) {
    restaurantList[i] = restaurants[i].getAttribute('value');
}



var searchBox = document.getElementById('pcategory');
var searchSubmit = document.querySelector('[type="submit"]');

function checkSearch() {
    if (restaurantList.indexOf(searchBox.value) === -1) {
        window.alert(searchBox.value + ' is not a valid selection - please choose from the list');
        searchBox.value = '';
    }
}

searchSubmit.addEventListener('click', checkSearch, false);
input {
width: 200px;
height: 40px;
font-weight: bold;
border: 1px thick rgb(127,127,127);
}
<form>
<input type="text" name="search" list="categoryname" autocomplete="off" id="pcategory" placeholder="Location or Restaurant" required/>
<datalist id="categoryname">
<option value="Nahid's Kitchen">Nahid's Kitchen</option>
<option value="Italian Dishes">Italian Dishes</option>
<option value="ABC Restaurant">ABC Restaurant</option>
</datalist>
<input type="submit" value="Search" />
</form>

关于javascript - 如何避免提交不在建议数据列表中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42623235/

相关文章:

jquery - 使用 jQuery 通过输入添加新的评级元素

php - 使用 PHP 从 MySQL 条目动态生成 select 标签

javascript - 在 javaScript 中使用 onclick() 调用 2 个不同的 div

javascript - 无法附加 jquery

JavaScript 引用错误 : min is not defined

javascript - 使用 AJAX 请求获取数组并将其传递到 php 数组

php - 对不同表上的列求和并乘以另一个表上的列的值

html - 封面背景图像未正确缩放?

javascript - 如何创建一个播放 mp3 google tts 的按钮

javascript - 如何在 Javascript/Ajax 中将多个值作为单个对象传递