Replace javascript alert

1

The system form I develop is full of alerts to warn the user that he can not leave that field unfilled and such. The problem is that the alerts are very annoying, and so I wanted to replace only with a color change in the input that he clicked, did not write anything, and then clicked off. In addition, it would be interesting to get a message when he clicks the button, such as the Facebook registration form (do the test clicking the field and then clicking outside). I know that nobody here works for me, for that very reason, if they helped me with which javascript event I would have to use to work this way would already be of great help.

For example, would I use an onkeypress, onclick, onblur ?? Another thing? I do not know.

And to make the message appear without being through a div with display none, would it be through a kind of validate massage ?? I do not know.

Help me

Ps. Developing in jsf + primefaces

    
asked by anonymous 29.01.2018 / 22:49

3 answers

3

One way to display a warning is to dynamically create a balloon next to input with CSS and JS.

The example below works with inputs and selects . Each field must be inside an element (in this case I put a span ). Just put the class validar and data-req with the text that will be displayed in the balloon.

See example:

var els = document.querySelectorAll(".validar");
for(var x=0; x<els.length; x++){
   els[x].addEventListener("blur", function(){
      if(this.value == ''){
         this.nextSibling.outerHTML = '';
         var alerta = document.createElement("span");
         alerta.setAttribute("class", "aviso");
         var t = document.createTextNode(this.dataset.req);
         alerta.appendChild(t);
         var seta = document.createElement("em");
         seta.setAttribute("class", "arrow-left");
         alerta.appendChild(seta);
         this.parentNode.insertBefore(alerta, this.nextSibling);
      }
   });

   els[x].addEventListener("focus", function(){
      this.nextSibling.outerHTML = '';
   });
}
*{
   position: relative;
}

.aviso{
   position: absolute;
   display: block;
   white-space: nowrap;
   padding: 5px;
   border-radius: 3px;
   top: 50%;
   left: 101%;
   background: #f30;
   color: #fff;
   z-index: 9;
   -webkit-transform: translateY(-50%);
   -moz-transform: translateY(-50%);
   transform: translateY(-50%);
}

.arrow-left {
  width: 0; 
  height: 0; 
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent; 
  border-right: 5px solid #f30;
  position: absolute;
  top: 50%;
  left: -5px;
  margin-top: -5px;
}
<span>
   <input class="validar" data-req="Campo obrigatório" type="text" />
</span>
<br /><br />
<span>
   <input class="validar" data-req="Campo obrigatório" type="text" />
</span>
<br /><br />
<span>
   <select class="validar" data-req="Campo obrigatório">
      <option value="">Selecione...</option>
      <option value="1">1</option>
   </select>
</span>
    
30.01.2018 / 22:57
2

I recommend using jQuery plugins quite popular among developers, two examples with great documentation and easy implementation are:

Advantages:

  • Both are plugins registered and listed by the official jQuery website.
  • The implementation in your application is fast and simple.
  • Plugins have already been tested and used by hundreds of developers, this will save you time on test drums you would do by creating your own nail script.
  • The UI (User Interface) is ready and tested on a variety of screen sizes, saving you time on test battery.
  • There are a lot of validations possible in fields, including regular expressions.
  • Simplifies the maintenance of your application by other developers.

Disadvantages:

  • Requires the jQuery Library.
  • Your application will get a few KB larger because of plugin loading.

It's important for you to know javascript and jQuery to develop your applications, but you do not even have to 'reinvent the wheel', study languages, use and understand ready-made libraries and plugins, your application will be completed in less time and you will learn much faster analyzing and using ready codes ...

    
30.01.2018 / 23:30
1

If you use jQuery, you can create a script like this (I just did it, but you can adjust it for your needs):

(function ($) {
  'use strict';

  $(function () {
    $('form').each(function () {
      var $form = $(this);

      /**
       * Prevenir o popup de requerido default.
       */
      $form
        .find('[required]')
        .removeAttr('required')
        .attr('data-required', 'true')
      ;

      $form.on('submit', function (event) {
        /**
         * Iterar sobre todos os elementos que tenham
         * o atributo 'required'.
         */
        $form
          .find('[data-required="true"]')
          .each(function () {
            var $this = $(this);
  
            /**
             * Caso o campo da iteração atual não esteja
             * vazio, passe para a próxima iteração.
             */
            if ($this.val() !== '') {
              $this.removeClass('is-not-valid');
              return;
            };

            /**
             * Caso algum campo esteja inválido,
             * previna a submissão do formulário.
             */
            event.preventDefault();
  
            $this.addClass('is-not-valid');
  
            if (!$this.attr('data-error')) return;
  
            /**
             * Criar a mensagem de erro após o campo.
             */
            $('<div>', { 'class': 'is-not-valid-error-container' })
              .append($('<span>', { 'text': $this.attr('data-error') }))
              .insertAfter($this)
            ;
          })
        ;
      });
    });
  });
}(jQuery));
.is-not-valid {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><div><label>Seunome:<br><inputtype="text" data-error="Qual o seu nome?" required>
    </label>
  </div>
  <div>
    <label>
      Sua idade: <br>
      <input type="number" data-error="Qual a sua idade?" required>
    </label>
  </div>
  <div>
    <label>
      Seu estado: <br>
      <select data-error="Qual o seu estado?" required>
        <option value="">Selecione uma opção</option>
        <option value="MG">MG</option>
        <option value="SP">SP</option>
        <option value="RJ">RJ</option>
      </select>
    </label>
  </div>
  <div>
    <br>
    <input type="submit" value="Enviar (ou testar :p)">
  </div>
</form>

In theory, the script looks for input 's that has the required attribute. If this field is empty, it adds a class ( is-not-valid ), and if it has a data-error="Erro que irá aparecer" attribute, the error will appear after the field.

See how the above code works, and do not forget to test it. It's worth stressing that you can make modifications to make it valid for your application.

I also reiterate that for your operation, you will need jQuery in your project (or develop a code with the same free idea as that library).

Now it's up to you! : D

    
30.01.2018 / 00:04