0
I have this select, where the user must select it:
<select asp-for="Configuracao.TipoEquipamento" class="form-control">
<option value="0">Catraca</option>
<option value="1">Fechadura</option>
</select>
But if he selects ratchet, the other select has to come filled this way:
<select asp-for="Configuracao.SentidoTeclado" id="cbSentidoTeclado" class="form-control">
<option value="I">Irrelevante</option>
<option value="E">Entrada</option>
<option value="S">Saída</option>
</select>
Otherwise he has to come filled as the following fields:
<select asp-for="Configuracao.SentidoTeclado" id="cbSentidoTeclado" class="form-control">
<option value="P">Principal</option>
<option value="S">Secundária</option>
<option value="D">Todos</option>
</select>
How can I change this at runtime via ajax? Several selects will have to be changed.
I’m trying to do it this way: but every time I click on cbTipoEquipment, it adds the data again:
$("#cbTipoEquipamento").change(function () {
//Pega o value da opção selecionada
let selectedValue = $("#cbTipoEquipamento option:selected").val();
//Depois disso, você pode fazer checar o valor do seu select e popular o outro select com as opções que você deseja.
if (selectedValue === '0') {
$("#cbSentidoTeclado").append($("<option />").val('I').text('Irrelevante'));
$("#cbSentidoTeclado").append($("<option />").val('E').text('Entrada'));
$("#cbSentidoTeclado").append($("<option />").val('S').text('Saída'));
} else {
$("#cbSentidoTeclado").append($("<option />").val('P').text('Principal'));
$("#cbSentidoTeclado").append($("<option />").val('S').text('Secundária'));
$("#cbSentidoTeclado").append($("<option />").val('D').text('Todos'));
}
});
Possible duplicate of How popular is a select with Jquery, JSON and AJAX ? (MVC)
– Ricardo Pontual
I need to know how popular depending on the value of another select, and it’s not data coming from the database, it’s static data.
– Mariana
Is that in the title of your question is "Change value select via ajax" :) Just return a list of values in the ajax call, which would be the data you want to put in select, and use the logic of the above example to put the data in the options
– Ricardo Pontual
I changed it to make it clearer.
– Mariana
It does not need to be a database query, just your ajax call returns a list/array with the pairs of values for the options
– Ricardo Pontual
Your code seems to me correct, I think we are missing only clean the previous items before making the append. You can do this using
empty()
, thus:$("#cbSentidoTeclado").empty()
– Ricardo Pontual
It worked, thank you.
– Mariana