I have a combobox and a table:
I would like every time when clicking the table, select the item in the combobox according to the click.
Following is an example of the problem.
Try to click multiple times in the table. At first it works, then it stops working.
var setores = [
{"id":"1", "setor":"Recepcao"},
{"id":"2", "setor":"Pronto Socorro"},
{"id":"3", "setor":"Unidade de Internacao"}
];
preencherComboBox();
preencherTabela();
function preencherComboBox(){
var combo = $('.select');
$.each(setores, function(i, setor){
combo.append($('<option>',{
value : setor.id,
text : setor.setor
}));
});
}
function preencherTabela(){
var tbody = $('.tbody');
$.each(setores, function(i, setor){
var linha = "<tr>"
+"<td>"+setor.id+"</td>"
+"<td>"+setor.setor+"</td>"
+"</tr>";
tbody.append(linha);
});
}
$('.tbody tr').on('click',function(e){
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
var setor = $.trim(tableData[0]) ;
$('.select option[value='+setor+']').attr('selected','selected');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script><divclass="form-group ">
<label>Itens</label>
<select class="form-control select col-lg-2"></select>
</div>
<table class="table table-responsive table-hover">
<thead>
<th>ID</th>
<th>Setor</th>
</thead>
<tbody class="tbody">
</tbody>
</table>