Gives Selected on certain value received in the JS function

1
> function
> editar_etapa_projeto(etapa_projeto_id,etapa_id,dias_total,data_inicial){
>     $('#etapa_projeto_id').val(etapa_projeto_id);
>     $('#etapa_id').find('option[value='+etapa_id+']').attr('selected',true');
>     $('#dias_total').val(dias_total);
>     $('#data_inicial').val(data_inicial); }

I want with this Javascript function, it fills the inputs of ids # such with the values received by input variables in the function.

It is working for the inputs, it takes the value of the variable, and plays in the value of the input.

But no select,

I need it to check the value that is received in the variable step_id, go to the id select #etapa_id, and a select in the select option where that value is.

$('#etapa_id').find('option[value='+etapa_id+']').attr('selected’,'true');

I have found that it selects yes, but by mistake in the selected="selected" compatibility firefox, it will not.

    
asked by anonymous 16.12.2015 / 18:58

4 answers

4

Use val similar to inputs:

$('#etapa_id').val(etapa_id);

Example:

$(document).on('click', '.setval', function(event){
	var etapa_id = $(this).data('val');
  
  $('#etapa_id').val(etapa_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><selectid="etapa_id">
  <option value="1">Valor 1</option>
  <option value="2">Valor 2</option>
  <option value="3">Valor 3</option>
  <option value="4">Valor 4</option>
  <option value="5">Valor 5</option>
</select><br><br>

<button class="setval" data-val="1">Setar Valor 1</button><br>
<button class="setval" data-val="2">Setar Valor 2</button><br>
<button class="setval" data-val="3">Setar Valor 3</button><br>
<button class="setval" data-val="4">Setar Valor 4</button><br>
<button class="setval" data-val="5">Setar Valor 5</button><br>

JSFiddle

    
16.12.2015 / 19:05
0

Failed " , see how it should be:

var el, valor;
el = $('#etapa_id').find('option[value="'+etapa_id+'"]')
el.attr('selected’,true');
valor = $('#etapa_id').val();
    
16.12.2015 / 19:07
0

Doing so will work:

    function editarEtapaProjeto(data) {
        for (var i in data) {
             $('#'+data[i][0]).val(data[i][1]);
        }
    }

    var data = [
                {'etapa_projeto_id', 1},
                {'etapa_id', 2},
                {'dias_total', 10},
                {'data_inicial', '2015-10-10 20:00:00'}
               ];
     editarEtapaProjeto(data);

Note: I reformatted the code to follow a formatting pattern.

    
16.12.2015 / 20:29
0

Missing updating select for firefox to work

    $('#etapa_id').selectmenu({ }); 
    
17.12.2015 / 17:08