How to select a <option> of <select> with javascript/jquery

Asked

Viewed 1,704 times

2

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

That one alert works perfectly, but I need it to be a code to select a option of select of functions in accordance with the data-funcao of the selected employee.

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

Select of employees:

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

Function select:

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

I’m using the jquery plugin Select2, I don’t know if it influences anything...

  • 1

    Forehead $('#id_mfuncao').select2('val', $("option:selected", this).attr('data-funcao')); in place of Alert. I think this is it. It tests and says here.

  • 1

    Po did work @Sergio, vlw!

  • Does anyone know how to do without jQuery?

1 answer

2


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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.