How to select a select option with javascript / jquery

2

I have two selects , one for employee and one for function, and it is necessary that when an employee is selected the function of that employee is already selected automatically.

This alert works perfectly, but I need instead to be a code to select a option of select of functions according to data-funcao of the selected employee.

$('#funcionario').on('change', function() {
    alert($("option:selected", this).attr('data-funcao'));
});

Employee Select:

<select id="funcionario" name="funcionario">
    <option value="..." data-funcao="...">...</option>
...
</select>

Select functions:

<select id="id_mfuncao" name="id_mfuncao">
    <option value="...">...</option>
...
</select>
  

I'm using the select2 jquery plugin, I do not know if it influences anything ...

    
asked by anonymous 08.08.2016 / 21:45

1 answer

2

Select2 has a .select2 method that serves almost everything. Passing val in the first argument and a value in the second one will look for in the options those that have this value. So you can use:

$('#funcionario').on('change', function() {
    var escolhido = $("option:selected", this).attr('data-funcao');
    $('#id_mfuncao').select2('val', escolhido);
});
    
08.08.2016 / 22:01