Count options from a select

0

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

    
asked by anonymous 09.11.2017 / 20:53

4 answers

1

To simply know how many elements exist 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><inputtype="button" value="Contar" />
    
09.11.2017 / 21:02
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><formid="form-listar-imovel" action="https://pt.stackoverflow.com/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><formid="form-listar-imovel" action="https://pt.stackoverflow.com/unanswered">
    
    <select  id="MeuSelect">
        <option>1</option>
    </select>
    
    </form>
    
09.11.2017 / 21:42
0

You can use the javascript childElementCount example ...

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.br" id="form">
     
    </form>
    
09.11.2017 / 21:08
0

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

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

};

Thanks to everyone

    
09.11.2017 / 21:19