How to use attr(Selected) in a dynamically created option?

Asked

Viewed 33 times

0

I have a table dynamically created and within it a select in which I use a map to create your options.

json.map(item => {
 var corpo = '';

 corpo += '<td>';
 corpo += '  <select>';
 arrStatus.map(item => {
   corpo += '  <option value="' + item.freteStatusID + '">' + item.status + '</option>';
 })
 corpo += '  </select>';
 corpo += '</td>'

 //adiciona esta linha na tabela
 $('#tabela').append(corpo);

 $('option[value=' + item.freteStatusID + ']').attr('selected', 'selected');
}

When I try to use the .attr within the map I receive this result with two options being selected

<select>
  <option value="5">Aceito pelo embarcador</option>
  <option value="2">Agendado</option>
  <option value="3">Declinado</option>
  <option value="1" selected="selected">Recebido</option>
  <option value="6" selected="selected">Rejeitado pelo embarcador</option>
  <option value="4">Removido</option>  
</select>
<select>
  <option value="5">Aceito pelo embarcador</option>
  <option value="2">Agendado</option>
  <option value="3">Declinado</option>
  <option value="1" selected="selected">Recebido</option>
  <option value="6" selected="selected">Rejeitado pelo embarcador</option>
  <option value="4">Removido</option>  
</select>

How can I make only one option by select take the "Selected attribute"?

1 answer

0


It seems your problem is in $('option[value=' + item.freteStatusID + ']')

In this query you are looking for all elements option with the value item.freteStatusID on your page, not just inside the select that you just created.

If in the first loop you look for a option with the value 1, and the second with value 6, it will assign the property selected for all the option present on your page with that value.

You don’t even need to do this separate query to add the property to your element, you can use a condition while building your HTML to add this property, example:

json.forEach(item => {
 var itemSelecionado = item.freteStatusID;
 var corpo = '';

 corpo += '<td>';
 corpo += '  <select>';
 arrStatus.forEach(item => {
   var selected = item.freteStatusID === itemSelecionado ? 'selected' : '';
   corpo += '  <option ' + selected + ' value="' + item.freteStatusID + '">' + item.status + '</option>';
 });
 corpo += '  </select>';
 corpo += '</td>';

 //adiciona esta linha na tabela
 $('#tabela').append(corpo);
}

Browser other questions tagged

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