Replace javascript Alert

Asked

Viewed 709 times

1

The system form I develop is full of Alerts to warn the user that he cannot leave that field without filling it out. The problem is that Alerts are very uncomfortable, and so I wanted to replace it with just one color change in the input that it clicks on, not write anything, and then click off. Also it would be interesting a message when he clicked on the button, like this one from Facebook registration form (Do the test by clicking on the field and then clicking out). I know that no one here works for me, so even so, if they helped me with what javascript event I would have to use to work this way would be of great help.

For example, would I use an onkeypress, onclick, onblur?? Something else? I don’t know.

And to make the message appear without being through a div with display None, would be through a kind of validate Massage?? I don’t know

Help me

Ps. I develop in jsf + primefaces

  • The way is to change the code where Alert is implemented, there is no way to replace the native javascript function called alert() by a personalized

  • If you want to know what each event does: onkeypress is when the key is pressed, onkeydown is when the key is pushed down onkeyup is when the key goes up. onblur the user takes the input focus of a certain form, onfocus is when the input of a form is "clicked"/focused. Just to guide you

  • Primefaces accepts this change?

  • @dvd accepts. In case my question now is just like showing up an explanatory message when hovering the mouse or clicking the input.

3 answers

4


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

The example below works with inputs and selects. Each field should be inside an element (in case I put one span). Just put the class validar and the 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>

  • Unfortunately the inputText of the first faces does not accept the 'data-req', says that this attribute has not been specified.

  • I’ll trade you for alt... just a moment.. The "alt" he accepts right?

  • he accepts yes!

  • I believe it is because even with inputText within span, when I inspect I see that each element is on a tr and td different.

2

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

Perks:

  • Both are plugins registered and listed by the official jQuery website.
  • Implementation in your application is fast and simple.
  • The plugins have already been tested and used by hundreds of developers, this will save you time in battery tests you would make creating your own script in the nail.
  • The UI (User Interface) comes ready and tested in various screen sizes, this saves you time in battery testing.
  • There is a very large amount of possible validations in fields, including regular expressions.
  • Simplifies maintenance of your application by other developers.

Disadvantages:

  • You need jQuery Library.
  • Your application will be some KB larger because of the plugin loading.

It is important to have knowledge of Javascript and jQuery to develop your applications, but even so you need to 'reinvent the wheel', study the languages, use and understand the ready-made libraries and plugins, your application will be completed in less time and you will learn much faster analyzing and using ready codes...

1

If you use jQuery, you can create a script more or less like this (I just did it, but you can adjust it to 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>
      Seu nome: <br>
      <input type="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'those with the attribute required.
If this field is empty, it adds a class (is-not-valid), and if you have an attribute data-error="Erro que irá aparecer", the error will appear after the field.

See how the code works above, and don’t forget to test it. It is worth noting that you can make modifications in order to make it valid for your application.

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

Now it’s up to you! D

Browser other questions tagged

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