Automatically select a select and press the button

3

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

What I need and I do not know is when I have in this my first <select> only one value, already selected, hence already make the call to that second select and already to activate the button even without the user select that second select.

For example, I have a% city% state and a city button. When selecting a state, the user can already press the button or select a city and press the button, only when there is only one state already selected this state and also already activate this button, giving only the user the option to select a city and then hit the button.

I hope I have not been too confused and 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 have only the State of São Paulo already select and hit the Search button, remembering that I have a function created that when the user selects the state 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 do not know if I need to pass all structure of this changeSelect function right.

    
asked by anonymous 26.03.2014 / 20:52

1 answer

1

Test to use if a select has only 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 some have only one option (maybe you wanted to use ==2 since it has the neutral text ---Selecione--- ). If you do not want to search all the selects the code can be simpler.

    
26.03.2014 / 21:10