Validate select fields by jquery

Asked

Viewed 768 times

1

I have a form using step Wizard as the link below:

https://bootsnipp.com/snippets/j6rkb

It works correctly, but I saw that the field validation only works for fields input. How could I validate also combobox fields? See below his jquery:

<script>
$(document).ready(function () {

    var navListItems = $('div.setup-panel div a'),
        allWells = $('.setup-content'),
        allNextBtn = $('.nextBtn');

    allWells.hide();

    navListItems.click(function (e) {
        e.preventDefault();
        var $target = $($(this).attr('href')),
            $item = $(this);

        if (!$item.hasClass('disabled')) {
            navListItems.removeClass('btn-success').addClass('btn-default');
            $item.addClass('btn-success');
            allWells.hide();
            $target.show();
            $target.find('input:eq(0)').focus();
        }
    });

    allNextBtn.click(function () {
        var curStep = $(this).closest(".setup-content"),
            curStepBtn = curStep.attr("id"),
            nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
            curInputs = curStep.find("input[type='text'],input[type='url']"),
            isValid = true;

        $(".form-group").removeClass("has-error");
        for (var i = 0; i < curInputs.length; i++) {
            if (!curInputs[i].validity.valid) {
                isValid = false;
                $(curInputs[i]).closest(".form-group").addClass("has-error");
            }
        }

        if (isValid) nextStepWizard.removeAttr('disabled').trigger('click');
    });

    $('div.setup-panel div a.btn-success').trigger('click');
});
</script>

The select would be that:

<select name="Estado" class="form-control" required="required">
   <option value="">Selecione</option>
   <option value="RJ">Rio de Janeiro</option>
   <option value="SP">São Paulo</option>
</select>

The complete code is found in the link I passed above, because I am copying faithfully as developed by the author.

  • When you talk combobox is referring to a select right?

  • Hello John, this... is a simple Bootstrap select.

  • I corrected the title with my post ;)

  • Show, I didn’t understand the combobox part.

  • I believe it would be nice if you put the html select to facilitate the understanding of the question.

  • Right. I put the select code in the post.

  • From the moment you build a select, it is assumed that the options are valid, so validate option that offers in select I find unnecessary, or am I mistaken?

  • I believe the correct question would be verificar se foi selecionado alguma opção em um select

  • 1

    Fox, if any answer has solved your problem you can mark as accepted by clicking the green V on the side of the chosen points. Or, if you want, you can leave it open for a while if you want more alternatives, but it is good that after it is resolved you mark some to close the subject. Learn more in "How and why to accept an answer".

  • 1

    Hello John. Done ;) Thank you!

Show 5 more comments

2 answers

1


To validate the fields of a select you have two options (which I know).

The first of these is using a required within the tag of the select (what you’re already doing).

<form id="form">
  <select name="Estado" class="form-control" required="required">
    <option value="">Selecione</option>
    <option value="RJ">Rio de Janeiro</option>
    <option value="SP">São Paulo</option>
  </select>
  <input type="submit" />
</form>

Recalling that the required not supported by Safari (others is normal, only Edge and IE which is only from version 10).

If you want to do something more personalized you can do it another way. See the example:

$('#estado').on('change', function(){
    $('#resultado').text(!!this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <select name="Estado" class="form-control" id="estado">
    <option value="">Selecione</option>
    <option value="RJ">Rio de Janeiro</option>
    <option value="SP">São Paulo</option>
  </select>
  <div id="resultado"></div>
</form>

From this you could do a customization in the style of the form you are implementing. See:

$('#estado').on('change', function() {
  if (this.value == false) {
    this.classList.add('error');
  } else {
    this.classList.remove('error');
  }
});
.error {
  border: 2px solid #a94442;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <select name="Estado" class="form-control" id="estado">
    <option value="">Selecione</option>
    <option value="RJ">Rio de Janeiro</option>
    <option value="SP">São Paulo</option>
  </select>
  <div id="resultado"></div>
</form>

Remembering that in the examples I used a little "pure" Javascript and in parts with jQuery. But, you could do everything only with jQuery, few things would change.

  • Can you explain these 2 exclamation marks

  • Look at this reply here from the SO explaining quite certain what the !! does.

  • found in Sopt https://answall.com/questions/29014/qual-o-sentido-de-usar-dupla-nega%C3%A7%C3%A3o-em-javascript

0

Form validation with jQuery

    $(document).ready(function () {

        $("#meuForm").validate({
            rules: {
                Estado: {
                    required: true
                }
            },
            messages: {
    Estado: "Selecione uma opção"
    
  },        
     submitHandler: function (form) { // para demo
                console.log('validado');
                return false;
            }
        });

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

<form id="meuForm">
  <select name="Estado" class="form-control" required="required">
        <option value="">Selecione</option>
        <option value="RJ">Rio de Janeiro</option>
        <option value="SP">São Paulo</option>
  </select>
        <br/>
        <input type="submit" value="Validar"/>
    </form>

  • Thank you all!

Browser other questions tagged

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