Reputation: 403
I have an form input of type datalist, in this list is about 5000 options, because of the large amount of options a select form just is not practical as you are allowed to type and it suggests what you want with a datalist.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2><label class='control-label' style="font-size: 20px;">Product code</label></h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
This is what i have now, however the user can type and submit things that are not in the list and i can not allow this. How can i stop this from happening?
Upvotes: 3
Views: 1178
Reputation: 19571
If you're willing to use jQuery UI's autocomplete
this would work:
<?php // tweak the below to use your data
$arr = array( array('Name' => 'one'), array('Name' => 'two'), array('Name' => 'three') );
$optsArr = array();
foreach ($arr as $a) {
array_push( $optsArr , '"'.htmlentities( $a["Name"] ).'"' ); ;
}
$options = implode(",", $optsArr)
?>
var availableTags = [<?php echo $options ?>];
$(function() {
$( "#ItemSelect" ).autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// ui.item property is null if the input was not found in the list
$("#ItemSelect").val("");
}
}
});
});
Upvotes: 0
Reputation: 32354
$('input[type="submit"]').on('click',function(e) {
$datalistval= $('#ItemSelect').val();
if ($('option[value="'+$datalistval+'"]').length == 0) //if no option is found alert the user
{
alert('incorect datalist value');
e.preventDefault();
}
});
jsfiddle: https://jsfiddle.net/ev63ghwk/
Upvotes: 2