您可以使用<input> 的list 属性和<datalist> 来实现您想要仅使用html 做的事情
<div class="col-md-3">
<div class="form-group">
<label for="custom_field1">{{ $contact_custom_field1 }}:</label>
<input id="custom_field1" name="custom_field1" type="text" list="custom_field1_datalist" class="form-control" placeholder="{{ $contact_custom_field1 }}">
<datalist id="custom_field1_datalist">
<option>Delhi</option>
<option>Goa</option>
</datalist>
<span id="error" class="text-danger"></span>
</div>
</div>
这将允许传递任何文本输入,因此您需要进行一些额外的验证。
$('#your-form-id').on('submit', e => {
$('#error').empty();
let form = $(e.target);
let validOptions = form.find('#custom_field1_datalist option').map((key, option) => option.value).toArray();
let customField1Value = form.find('input[name=custom_field1]').eq(0).val();
// check if custom_field_1's value is in the datalist. If it's not, it's an invalid choice
if ( !(validOptions.indexOf(customField1Value) > -1) ) {
// show error
$('#error').text('Invalid Choice');
// prevent form submission (you should still validate in the backend)
e.preventDefault();
}
});
另外,由于您已使用 JQuery 标记标记此问题,因此您可以使用像 select2 这样的库并让它为您执行此操作。
你只需要把它放在你的<head>标签中
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
将select2 类添加到您的选择中。
<select name="custom_field1" class="form-control select2" placeholder="Select City" required>
<option>Delhi</option>
<option>Goa</option>
</select>
然后,在您的 javascript 中,将其添加到您的 $(document.ready(...) 块中。
$(document).ready(function() {
$('.select2').select2();
});