I have this checklistbox.
<div class="col-md-6">
<h3 class="text-center">Unidade de negócio</h3>
<div class="well" style="max-height: 300px;overflow: auto;">
<ul class="list-group checked-list-box" id="chkLista">
<li class="list-group-item" data-style="button">DERMA RX / ONCO</li>
<li class="list-group-item" data-style="button" data-color="success">DERMOCOSMÉTICOS</li>
<li class="list-group-item" data-style="button" data-color="info">GENÉRICOS</li>
<li class="list-group-item" data-style="button" data-color="warning">EXPORTAÇÃO</li>
<li class="list-group-item" data-style="button" data-color="danger">MIP</li>
<li class="list-group-item" data-style="button">PRESCRIÇÃO</li>
</ul>
</div>
</div>
I need to check some item in the list and get this item via jquery and then send it to a controller. Send to controller, no problem. I can not get the item via jquery.
This is my jquery
function Teste() {
var realvalues = [];
var textvalues = [];
$('#chkLista :selected').each(function (i, selected) {
realvalues[i] = $(selected).val();
textvalues[i] = $(selected).text();
alert(i);
});
alert(realvalues);
}
Do not fire Alert (i), ie do not enter each. Any help is welcome.
I did this and it did not work.
var checkedItems = {}, counter = 0;
function GravaCargo() {
$('#get-checked-data').on('click', function (event) {
event.preventDefault();
$("#check-list-box li.active").each(function (idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});
var str = "";
alert(JSON.stringify(checkedItems, null, '\t'));
$.ajax({
url: '/CadastroCargo/GravaCargo',
datatype: 'json',
contentType: 'application/json;charset=utf-8',
type: 'POST',
data: JSON.stringify({ _cargo: checkedItems }),
success: function (data) {
},
error: function (error) {
}
})
}
In the search for a response, I did it this way and managed to get something in the controller, but the next format is kind of strange, since it has \ n \ t \ 0: name1, \ n \ t \ 1: name2 and what I'm interested in name1 and name2. How do I clean it? Here's how it went:
var checkedItems = {}, counter = 0;
function GravaCargo() {
$("#check-list-box li.active").each(function (idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
var str = "";
var valor = JSON.stringify(checkedItems, null, '\t');
$.ajax({
url: '/CadastroCargo/GravaCargo',
datatype: 'json',
contentType: 'application/json;charset=utf-8',
type: 'POST',
data: JSON.stringify({ _cargo: valor }),
success: function (data) {
},
error: function (error) {
}
})
}
Method in my controller
[HttpPost]
public void GravaCargo(string _cargo)
{
using(RupturaEntities db = new RupturaEntities())
{
Cargo crg = new Cargo();
try
{
crg.NM_Cargo = _cargo;
db.Cargo.Add(crg);
db.SaveChanges();
}
catch(Exception ex)
{
Erro = "Erro na gravação do registro: " + ex.Message;
}
}
}