要求输入在datalist中

时间:2015-04-09 08:02:46

标签: javascript jquery html

我有一个类型为datalist的表单输入,在这个列表中有大约5000个选项,因为大量的选项,选择表单是不实际的,因为你可以键入它,它建议你想要的数据列表。

 <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>

这就是我现在所拥有的,但是用户可以输入和提交不在列表中的内容,我不能允许这样做。我怎么能阻止这种情况发生?

2 个答案:

答案 0 :(得分:1)

如果字段具有incorect值

,则提醒用户
$('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/

答案 1 :(得分:0)

如果您愿意使用jQuery UI&#39; autocomplete,这可行:

  <?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("");
            }

        }
     });
 });

这里是working Demo