Force user to select an item in input type datalist

0

Good evening guys, I have the following code in a hotel system that I'm putting together:

<?php 
    include "Hospede.php";
    $newHospede = new Hospede();
    $rs = $newHospede->listarNomesHospedes();
    $qtdHospedes = mysql_num_rows ($rs);
?>
<input list="hospedes" name="hospede" id="hospede" required>
<datalist id="hospedes">
    <?php
        for ($cont = 0; $cont < $qtdHospedes; $cont++){
            $nome = mysql_result ($rs, $cont, "nome");
    ?>
        <option value="<?php echo $nome; ?>">
    <?php
        }
    ?>
</datalist>

The guest field has a list of the guest names that the query in the database returned, but I'm having a problem: Because the datalist field allows the user to type to fetch an item from the list, it is it is possible for the user to type anything and submit the form, since the "required" attribute of the HTML leaves only the fact that the user has typed something inside the field. I need to find a way to force the user to select an item from the list. If you can help, thank you.

    
asked by anonymous 20.04.2017 / 02:22

1 answer

1

Script:

  

The variable wordsAceitas should contain exactly the values of the datalist options.

var palavrasAceitas = ["Samba", "Blues", "Jazz", "MPB", "Rock", "Clássico", "bossanova", "Pop"],
regex = new RegExp('\b' + palavrasAceitas.join("\b|\b") + '\b', 'i');

 $(function () {
      $("input").on("change", function () {
      var valid = regex.test(this.value);
         if (valid==false){
             alert ("Termo não existente na lista");
         }
       });
  });

  function vazio() {
     var x;
     x = document.getElementById("estilo").value;
     if ((x == "")||(x == null)) {
        alert("Selecione uma opção");
        return false;
     };
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><formaction="" method="post">
  <fieldset>
    <legend>Música</legend>
    <label for="estilo"> Qual o seu estilo musical ?</label>
    <input id="estilo" name="estilo" type="text" list="listaestilos"/>
        <datalist id="listaestilos"><br/>Escolha entre estes:
            <option value="samba">Samba</option>
            <option value="blues">Blues</option>
            <option value="jazz">Jazz</option>
            <option value="mpb">MPB</option>
            <option value="rock">Rock</option>
            <option value="clássico">Clássico</option>
            <option value="bossanova">Bossanova</option>
            <option value="pop">Pop</option>
        </datalist>
    </fieldset>
    <input type="submit" onClick="return vazio()">
   </form>
  

BONUS to fix the problem described in the comment.

     

Creating the variable wordsAccepts dynamically for use in the script:

<?php 
  include "Hospede.php";
  $newHospede = new Hospede();
  $rs = $newHospede->listarNomesHospedes();
  $qtdHospedes = mysql_num_rows ($rs);
?>
 <input list="hospedes" name="hospede" id="hospede" required>
 <datalist id="hospedes">
 <?php
    for ($cont = 0; $cont < $qtdHospedes; $cont++){
        $nome = mysql_result ($rs, $cont, "nome");
        $palavrasAceitas=$palavrasAceitas.chr(34).$nome.Chr(34).",";
 ?>
    <option value="<?php echo $nome; ?>">
 <?php
    }
    $palavrasAceitas = substr($palavrasAceitas,0,-1);
    $palavrasAceitas=("var palavrasAceitas = [".$palavrasAceitas."],\nregex = new RegExp('\\b' + palavrasAceitas.join(".Chr(34)."\\b|\\b".Chr(34).") + '\\b', 'i');");
 ?>
 </datalist>

 <script language="javascript">

 <?php echo $palavrasAceitas ?>

   $(function () {
      $("input").on("change", function () {
         var valid = regex.test(this.value);
         if (valid==false){
            alert ("Termo não existente na lista");
         }
      });
   });

   function vazio() {
      var x;
      x = document.getElementById("estilo").value;
      if ((x == "")||(x == null)) {
          alert("Selecione uma opção");
          return false;
      };
   }
  </script>
    
20.04.2017 / 04:56