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?
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?
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" />
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>
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>
I got what I wanted. I'm new to jquery
if ($('#municipio-index option').size() == 1){
$('#form-listar-imovel').submit();
};
Thanks to everyone