Problem with jquery in a select

0

I am using the model MVC with PHP v7. , HTML5 and SQL server 2008 , I have a page where I display a certain list and for each record I have a button to update.  Pressing the button calls a function in JS , which through AJAX , brings the information to be updated in a form. In the form I have a SELECT where I want to load the information, this shows the option with which I saved before.  I have made the loading with several options, but only if I open the SELECT the selected option appears but it is not shown in the SELECT , it is only shown if I deploy it.

I used the following code Jquery :

$("#field option[value="+info+"]").attr("selected", "selected");

$("#field option[value="+info+"]").attr("selected", true);

$("#field").val(info.trim()).attr('selected', "selected");

$('select[name="field"]').find('option[value='+info+']').attr("selected", true);

document.querySelector('#field-8 [value="' + info + '"]').selected = true;

All if you select the value they should but in the text is not displayed.

Example that if you select the option you should:

But when loading the information that must be updated, it appears:

    
asked by Irais_Rivero 04.09.2017 в 18:06
source

2 answers

0

With some libraries, like select2 for example, you have to do trigger of the event change to show you the result .

Try that way:

$("#field").trigger("change");
    
answered by 04.09.2017 / 18:22
source
0

You just have to use the function .trigger(<evento>) , I leave you a short example

$(document).ready(function(){
  setTimeout(function(){
    $('select').val("2");
    $('select').trigger('change');
  }, 2000)
});
select{
  width: 100%;
  padding: 12px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="0">-- Seleccionar --</option>
  <option selected="" value="1">Opción 1 (seleccionada por defecto)</option>
  <option value="2">Opción 2 (seleccionada por jQuery)</option>
  <option value="3">Opción 3</option>
</select>
    
answered by 04.09.2017 в 18:32