Validation of select

Asked

Viewed 6,753 times

1

I have the following HTML

<select class="cadastroDireitaInput cadastroSiteSexo" id="sexo" name="sexo">
  <option value="">Selecione</option>
  <option value="Feminino">Feminino</option>
  <option value="Masculino">Masculino</option>
</select>

I have a JS that checks if the fields are filled in, for example, this line of code:

if($.trim($('#nomeFormUS').val())=='')alert('Informe seu nome!');

In this case, it checks whether an input is filled in.

Now, how do I check if any Options have been selected from that Select?

  • It’s the same thing, with jQuery.val().

  • I managed to solve the problem?

3 answers

2

I use it this way:

<script>
if(nome_formuario.nome_do_select.selectedIndex==0){
            alert("Informe o status do contrato");
            form.st_contrato.focus();
            return false;
        }
</script>

1

but the correct one would already bring as a standard some sex ... simple problem and unless to worry

  $('#sexo').change(function(){
       var value = $(this).val();
          if(value == ''){
            alert('Escolha um sexo');        
        }
    });

1

You can use the .val() also or use pure javascript .value

Take a look at this example that makes "false" Lert when choosing the first option and "true" in the others:

$('#sexo').on('change', function(){
    $('#resultado').text(!!this.value);
});

Demo: jsFiddle

So your code could be: (jsFiddle)

 if(!this.value) alert('Informe seu sexo!');
  • If I just want it to check whether it is marked or not without showing. Just remove the $('#resultado').text(!!this.value + ' ' + this.value);?

  • 1

    @Felipestoker, I’ve made an update: if(!this.value) alert('Informe seu sexo!');

  • This is the only place Fiddle hasn’t opened in weeks?

  • @Brunoaugusto jsFidle has been receiving an upgrade. Here at Uécia it already works

  • @Sergio, just a doubt. What would the syntax look like, following this structure of mine? He was good in his example, but I must have included him wrong. http://jsfiddle.net/felipestoker/nnfvge9f/

  • @Felipestoker put here a fiddle with HTML and I can show a much simpler way.

  • @Felipestoker I’m actually beginning to think that your question is very similar to this one: http://answall.com/q/28085/129

  • @Sergio, man I created confusion. Your answer helped me, but I realized I can use the same used in others: Example else if($.trim($('#sexo').val())=='')alert('Informe o seu sexo!');&#xA; I just want him to see whether or not the option is checked. Thanks :)

  • 2

    @Felipestoker, you’re doing more complicated than you need to. It’s always better to use pure javascript than jQuery. If you want to put HTML I can help simplify.

Show 4 more comments

Browser other questions tagged

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