How to make the last "click" on an option that is in a for ()?

1

The variable ${window.nombre} is a global variable that contains the id of a magazine, but it is not selected when I click the button of the magazine, it always brings me to the last value of select .

$.ajax({

        url:'MODEL/Menu_Model.php',
        success:function(data){
            $(".square_select_revistas").html("");
            var Data=JSON.parse(data);
            for (var i = 0; i < Data.length; i++) {
                var select = '
                    <option selected="${window.nombre}" value="${Data[i].id}" >
                        ${Data[i].nombre_revista}
                    </option>
                '
                $(".square_select_revistas").append(select);
            }
        }
    });

var modal = '

  <div class="square_modal col-sm-7">

      <label>Revista</label><br>

      <select id="revista" 

            class="square_select_revistas">

      </select>
  </div>
';
    
asked by user9151513 11.01.2018 в 06:18
source

1 answer

1

The "selected" attribute can be used in two ways:

<option selected>Algún valor</option>
<option selected="selected">Algún valor</option>

If you want the magazine whose id is the variable $ {window.name} you select, you should do the following:

$.ajax({

    url:'MODEL/Menu_Model.php',
    success:function(data){
        $(".square_select_revistas").html("");
        var Data=JSON.parse(data);
        for (var i = 0; i < Data.length; i++) {
         if(Data[i].nombre_revista == ${window.nombre}){
            var select = '
                <option value="${Data[i].id}" selected>
                    ${Data[i].nombre_revista}
                </option>';
         }else{
            var select = '
                <option value="${Data[i].id}" >
                    ${Data[i].nombre_revista}
                </option>';
         }
            $(".square_select_revistas").append(select);
        }
    }
});

This way you are comparing the name of the global variable with the names that the AJAX request returns and assigning the "selected" attribute only to the element that matches.

    
answered by 11.01.2018 в 08:46