Change value select via ajax as another select with static data

Asked

Viewed 473 times

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'));
        }
    });
  • 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.

  • 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

  • I changed it to make it clearer.

  • 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

  • 1

    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()

  • It worked, thank you.

Show 2 more comments

2 answers

2


You must create an Event Listener for the change of the first select, put an ID in your select and include the script:

$("#selectId").change(function(){
    //Pega o value da opção selecionada
    let selectedValue = $("#selectIdoption: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') {

    } else { 

    }
});

I believe that you do not need to ajax in this case unless the options are loaded from a database or Web Service, if they are, you will need to create the api to load the options according to the value of select. Otherwise, it is only popular with Javascript the selects with the following code for each option:

$("#selectId").append($("<option />").val('valueDaOpcao').text('textDaOpcao'));
  • I tried to do this way, but every time I click on cbTipoEquipment, it adds again the same options, I will update the question of how I am doing.

  • I cleaned up before including them and it worked, thank you.

0

Since you won’t consult in the database, you can make an array in javascript just waiting to put combobox when choosing the option

var catraca = 
       [
          {value: 'I', text: 'Irrelevante'},
          {value: 'E', text: 'Entrada'},
          {value: 'S', text: 'Saída'},
       ]
       
 var fechadura = 
       [
          {value: 'P', text: 'Principal'},
          {value: 'S', text: 'Secundária'},
          {value: 'D', text: 'Todos'},
       ]
       $( document ).ready(function(){
         mudar(0);
       })
       
       $('.equipamento').on('change', function(){
          var choose = $(this).val()
       //   console.log( choose )
          mudar( choose )
       })
       
       function mudar( esc ){
          var comboBox = $('#comboBox')
          var option = "";
          var local = [];
          
          if( esc == 0 ){
          //console.log('Catrada')
            local = catraca;            
          } else{
          //console.log('Fechadrua')
            local = fechadura;
          }
          //console.log( local )
          $.each( local, function(i, j){
             option += "<option value='"+j.value+"'>"+j.text+"</option>"
          } )
          
          comboBox.find('option').remove()
          comboBox.append( option )
       }
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<select asp-for="Configuracao.TipoEquipamento" class="form-control equipamento" >
  <option value="0">Catraca</option>
  <option value="1">Fechadura</option>
</select>

<select id="comboBox" class="form-control">
        
  </select>
<!--
 <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>
Senão ele tem que vim preenchido como os seguintes campos:

<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>
                                -->

Browser other questions tagged

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