javascript – Automatically select a select and press the button

Question:

I have a field like <select> / <option> that when the user selects a value I call a function to populate another <select> , like the state and city combos, this is working, and then the user clicks on one button that makes an ajax call to bring up some data to display.

What I need and I don't know is when I have in my first <select> only one value, already selected, then I make the call to this second select and already press the button even without the user selecting this second select.

For example I have a state select other than city and a button. When selecting a state, the user can already click on the button or select a city and click on the button, but when there is only one state, that state is already selected and that button is already clicked, giving only the user the option to select a city and then press the button.

I hope I haven't been too confused and that they can understand to be able to help me.

<label for="estado">
<select>
    <option value="0"> ---Selecione--- </option>
    <option value="SP"> São Paulo </option>
</select>

<label for="cidade">
<select>
    <option value="0"> ---Selecione--- </option>
</select>

<button type="submit" id="listarItens">Buscar</button>

In this case, if you only have the State of São Paulo, you already select and click on the Search button, remembering that I have a function created that when the user selects the state it calls this function.

$(document).ready(function() {
    changeSelect('estado', ['cidade'], 'selecionaCidades.php');

    $('#listarItens').click(function(event){
        event.preventDefault();
        //aqui executa algumas coisas como um ajax, mas isso acho que não preciso listar correto
    });


});

I don't know if there's a need for me to pass the entire structure of this changeSelect function right.

Answer:

Try using it like this to find out if a select only has one option:

$('select').each(function () {
    var options = $(this).find('option');
    var qtdOptions = options.length;
    if (qtdOptions == 2)  {      // uso dois porque a sua primeira option é só uma guia
        this.selectedIndex = 1;  // escolher a segunda option
        $("select[name='estado']").change();
        $('#listarItens').trigger('click');  // carregar no botão!
    }
});

Example

This code looks for all selects and if any have only one option (maybe you want to use ==2 since it has neutral text ---Selecione--- ). If you don't want to search for all the selects the code can be simpler.

Scroll to Top