Catch value on an item checked from a checklistbox

1

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;
                }
            }
        }
    
asked by anonymous 25.08.2014 / 17:41

1 answer

2

According to link , follow the example below:

Html

<div class="col-xs-6">
    <h3 class="text-center">Colorful Example</h3>
    <div class="well" style="max-height: 300px;overflow: auto;">
        <ul id="check-list-box" class="list-group checked-list-box">
          <li class="list-group-item">Cras justo odio</li>
          <li class="list-group-item" data-color="success">Dapibus ac facilisis in</li>
          <li class="list-group-item" data-color="info">Morbi leo risus</li>
          <li class="list-group-item" data-color="warning">Porta ac consectetur ac</li>
          <li class="list-group-item" data-color="danger">Vestibulum at eros</li>
        </ul>
        <br />
        <button class="btn btn-primary col-xs-12" id="get-checked-data">Get Checked Data</button>
    </div>
    <pre id="display-json"></pre>
</div>

Javascript

$('#get-checked-data').on('click', function(event) {
        event.preventDefault(); 
        var checkedItems = {}, counter = 0;
        $("#check-list-box li.active").each(function(idx, li) {
            checkedItems[counter] = $(li).text();
            counter++;
        });
        $('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
    });

Solution

In your particular case

function Teste() {        
    var checkedItems = {}, counter = 0;
    $("#chkLista li.active").each(function(idx, li) {
        checkedItems[counter] = $(li).text();
        counter++;
    });
    alert(JSON.stringify(checkedItems, null, '\t'));
}
<button class="btn btn-primary col-xs-12" onclick="Teste()">Verificar Itens Escolhidos</button>

OnLineExample: JSFiddle

Part of Submission to Controller

Javascript

$.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) {
            }
});

Controller Method CadastroCargo

public ActionResult GravaCargo(Dictionary<string, string> _cargo)
{
            return View();
}

    
25.08.2014 / 17:51