Show required message in an input="select"

3

I have a form with the following structure:

<input type="text" required="" />
<select required="required">
  <option disabled="disabled" selected="selected">Selecciona un ID...</option>
</select>
<input type="text" required="" />
<input type="submit" />

As you can see, I suppose you already know my problem, in the same way I explain it to you ... I must select an ID and write text, in case one of these fields are empty, the message corresponding to the type jumps out, this is done in the input type="text" this does well except in the select this is because having the selected="selected" the field is no longer empty, my question is if there is a way to verify that you select a different option to the one selected by default and in case you do not select any show the message equal to the other inputs?

EDITED

    
asked by Francisco Fernandez 13.09.2016 в 20:13
source

2 answers

3

$("#mySelect").change(function(event) {
    if($(this)[0].selectedIndex==0)
      {
        $(this).prop('required',true);
        $("#txtFin").val('');
      }
      else
      {
      	$(this).prop('required',false);
      	$("#txtFin").val($("#mySelect option:selected").val());
      }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" accept-charset="utf-8">	
	<select  id="mySelect" required>
	  <option value="">Selecciona un ID...</option>
	  <option  value="a">Selecc...</option>
	  <option  value="b">Se...</option>
	  <option  value="c">Ja</option>
	</select>
	<input type="text" id="txtFin" />
	<input type="submit" />
</form>
    
answered by 13.09.2016 / 21:01
source
0

Well, here I leave a possible answer to your question. I assume you work with jQuery

This is a way to solve it.

//Usamos mediante Jquery una funcion que ejecute un algoritmo cuando se inicie el evento submit (enviar) del formulario
$( "form" ).submit(function( event ) {
  //Ahora buscamos el select y verificamos que opcion esta elegido
  $("select option:selected",this).each(function (a){
    if(a == 0){ //En dado caso que este elegida la opción 0 (en el indice de los options.
      alert("Por favor elige una Id del Menu Select"); // entonces procedemos a ingresar la alerta 
      $("select").focus(); // Agregamos foco al Select
      return false; //Retornamos falso en formulario para que no permita el envio
    }

  });
  event.preventDefault(); //Detenemos los eventos.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <input type="text" required="" />
<select> <!-- Primero quitamos todos los atributos del select -->
  <option >Selecciona un ID...</option>
  <option> Opcion Uno</option>
    <option> Opcion Dos</option>
      <option> Opcion Tres</option>
</select>
<input type="text" required="" />
<input type="submit" />
  </form>
    
answered by 13.09.2016 в 21:19