Validate input with ajax populated values

Asked

Viewed 17 times

-1

Oops! One more than taking a beating.

I have an input that is auto populated via ajax, as you type the search ajax and go listing results in <li> in a <div> below the input. Type the image below.

inserir a descrição da imagem aqui

However, the code today allows the user to submit the form with anything written in the input.

And I want him must click on something in the list, if not, it will not be possible to proceed.

My codes.

The input:

<div class="col-md-5 text-center">
    <input class="form-control form-control-lg text-muted mb-3" type="text" id="busca" autocomplete="off" name="busca" placeholder="Digite Bairro ou Cidade">
    <div id="buscalist" style="position:absolute;z-index:99;"></div>
</div>

The script:

<script type="text/javascript">
  $(document).ready(function(){
      $("#busca").on("keyup", function(){
        var busca = $(this).val();
        if (busca !=="") {
          $.ajax({
            url:"action.php",
            type:"POST",
            cache:false,
            data:{busca:busca},
            success:function(data){
              $("#buscalist").html(data);
              $("#buscalist").fadeIn();
            }  
          });
        }else{
          $("#buscalist").html("");  
          $("#buscalist").fadeOut();
        }
      });
      $(document).on("click","#buscas li", function(){
        $('#busca').val($(this).text());
        $('#buscalist').fadeOut("fast");
      });
  });
</script>

php action.

<?php
include_once ("config.php");
    if (isset($_POST['busca'])) {
        $output = "";
        $busca = $_POST['busca'];
        $query = "SELECT dataatualizacao, bairro, cidade FROM imoveis WHERE bairro LIKE '%$busca%' OR cidade LIKE '%$busca%' AND (dataatualizacao >= (DATE(NOW()) - INTERVAL ".$diasatualizados." DAY)) GROUP BY bairro";
        $result = $MySQLiconn->query($query);
        $output = '<ul id="buscas" class="list-unstyled" style="background-color:#fff;padding:8px;color:#6c757d;cursor: pointer;">';        
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_array()) {
                $output .= '<li><i class="fas fa-map-marker-alt"></i> '.ucwords($row['bairro']).', '.ucwords($row['cidade']).'</li>';
            }
        }else{
              $output .= '<li><i class="far fa-times-circle"></i> Conteúdo não encontrado</li>';
        }
        
        $output .= '</ul>';
        echo $output;
    }
?>

And I’ve tested some things within my knowledge, but I’ve only generated more problems. Like, logic ran out. That’s why I’m here, asking for more help. If you can give me a north, it will be of great value. Grateful

1 answer

0

A simple solution would be to put a hidden input that will be populated with what the user selects.

<div class="col-md-5 text-center">
    <input class="form-control form-control-lg text-muted mb-3" type="text" id="busca" autocomplete="off" name="busca" placeholder="Digite Bairro ou Cidade">
    <input id="busca_result" type="hidden">
    <div id="buscalist" style="position:absolute;z-index:99;"></div>
</div>

Jquery

$(document).on("click","#buscas li", function(){
    $('#busca').val($(this).text());
    $('#busca_result').val($(this).text());
    $('#buscalist').fadeOut("fast");
});

Then you validate the form to see if the result was clicked, something like:

$('#meuForm').submit(function( event ) {
    if(!$('#busca_result').val()){
         event.preventDefault();
    }
}); 
  • That’s it brother! It worked! I just need to present something like "You need to click below" or not need, very good!. Note: I am new, I can not even score the answer. Gratitude brother.

  • 1

    Put a label on your input to inform the user, UX... To also force the user to click you can clear the search field if the user does not select from your list... see jQuery focusout ... something like $( "#busca" ).focusout(function() { if(!$(this).val()){ $(this).val('') }})

  • Caiovisk gratitude.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.