Count options from a select

Asked

Viewed 1,375 times

0

I need to count the options of a select. If you only have 1 option, I submit the form. How do I do this in jQuery?

4 answers

1

To simply know how many elements there are inside another you can try to retrieve them, something like this:

let options = $("select option"); // options.length irá indicar qtd de elementos

Example

$("input").click(function() {
    let opts = $("select option");
    console.log(opts.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
    <option>1</option>
    <option>2</option>
</select>

<input type="button" value="Contar" />

1

With two options, do not submit

if($('#MeuSelect option').size()==1){
    $('#form-listar-imovel').submit();
};
console.log($('#MeuSelect option').size());
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form id="form-listar-imovel" action="/unanswered">
    
    <select  id="MeuSelect">
        <option>1</option>
        <option>1</option>
    </select>
    
    </form>

With an option, submit

if($('#MeuSelect option').size()==1){
    $('#form-listar-imovel').submit();
};
console.log($('#MeuSelect option').size());
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form id="form-listar-imovel" action="/unanswered">
    
    <select  id="MeuSelect">
        <option>1</option>
    </select>
    
    </form>

0

You can use childElementCount from the example javascript...

if(document.querySelector('select').childElementCount > 1)
console.log('mais de 1 > submit: ' + document.getElementById('form').submit); 
    <select>
      <option>teste</option>
      <option>teste</option>
    </select>

    <form action="https://www.google.com" id="form">
     
    </form>

0

I got what I wanted. I’m new to jquery

 if ($('#municipio-index option').size() == 1){
                $('#form-listar-imovel').submit();

};

Thank you all

Browser other questions tagged

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