How to make an input not accept blank input?

Asked

Viewed 1,886 times

-1

<head>
    <title>WEB VIDEO AULAS</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <!-- Latest compiled and minified CSS -->


</head>
<body>
<br/>   <br/>   <br/>   <br/>   <br/>
    <div class="container">

        <div class="row">
            <div class="col-lg-3">
                <div class="input-group">
                    <input type="text" class="form-control" size="35" id="palavra" placeholder="Digite seu nome ou sua matrícula.." required />
                    <span class="input-group-btn">
                        <button class="btn btn-blue" id="buscar" type="button">Buscar</button>
                    </span>
                </div>
            </div>
        </div>
        <div id="dados"></div>
    </div>
     <link rel="stylesheet" href="/SLP/css/css/CDTpag1.css">
    <script>


        function buscar(palavra)
        {
            var page = "/SLP/css/css/busca.php";
            $.ajax
                    ({
                        type: 'POST',
                        dataType: 'html',
                        url: page,
                        beforeSend: function () {
                            $("#dados").html("Carregando...");
                        },
                        data: {palavra: palavra},
                        success: function (msg)
                        {
                            $("#dados").html(msg);
                        }
                    });
        }


        $('#buscar').click(function () {
            buscar($("#palavra").val())
        });
    </script>

</body>

  • Blank would be just spaces or blank would be no value inserted? Your question has no description to help you better understand the problem. I suggest you make an edit.

  • possible duplicate https://answall.com/questions/193371/comorvalidar-campos-em-branco-em-html/193574#193574

4 answers

1

If I understand correctly, you don’t want the input is not empty or contains only space.

I’d do some simple like that:

$('#buscar').click(function () {

     var $palavra = $('#palavra');


     $palavra.val().trim().length && buscar($palavra.val());

      // ou

      if ($palavra.val().trim().length) {
          buscar($palavra.val());
      }
});

The sentence $palavra.val().trim().length assess whether the value of false or not through the number returned. If it is zero, the function will not be executed buscar. That’s because the trim removes blanks from the beginning and end of String.

Another option without jQuery, in my opinion, would be defining a required in the input desired and adding functionality in onchange to remove spaces from start and end.

<form>
<input type="text" required onchange="this.value = this.value.trim()">
<button type='submit'> Enviar </button>
</form>

0


How you are capturing the event click of the element #palavra, the browser ends "overtaking" of the field check and running the function buscar().

When you "submits/" the form, the browser itself checks the attributes required and pattern before proceeding.

So change the function call buscar():

        $('#buscar').click(function ()
        {
            if( $('#palavra').val() != '' && $('#palavra').val() != 'undefined' && $('#palavra').val() != null $('#palavra').val() != ' ' )
            {

                buscar($("#palavra").val())

            } else
            {
                alert("Você deve inserir seu nome ou matrícula!");
                return false;
            }
        });

In my code I checked if the field is empty, but you can put a regular expression for example.

I put a alert in case of invalid entry, which can be replaced by a code to your liking, such as showing an error div below the input for example.

Tested with Google Chrome!

Now, use your imagination!

0

I believe you can only use jquery to do all the checking necessary for this simple search. I would make a modification only in this part.

$('#buscar').click(function () {
  var keyword = $("#palavra").val();    // O valor pode ser algo como: '     oi     '
      keyword = $.trim( keyword );      // o trim vai remover os espacos do comeco e do fim: 'oi'
  if( keyword.length ){
    buscar( keyword );
  } else {
    alert( 'Busca em branco' );
  }
});

0

Add Pattern to your input. So it will allow only words. If user type multiple spaces it will not pass

<input type="text" class="form-control" size="35" id="palavra" placeholder="Digite seu nome ou sua matrícula.." required pattern="^[^-\s][a-zA-ZÀ-ú ]*">

You can also validate in javascript

$('#buscar').click(function () { 
      if( $("#palavra").val().length < 1 ) { 
          Alert("digite uma palavra")
          return false;
      } else {
          buscar( $("#palavra").val() );
      }
 });

Browser other questions tagged

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