Pick up value on a checkbox checked item

Asked

Viewed 597 times

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’m not getting 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);
}

Does not fire Alert(i), IE, does not enter each. Any help is welcome.

I did it and it didn’t 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 answer, I did this way and I got something in the controller, but the format that comes is kind of strange, because it has n t 0:name1, n t 1:Nome2 and what interests me is name1 and Nome2. How do I clean it up? Look how it turned out:

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;
                }
            }
        }
  • You are searching for the value of elements <li> that are not inputs... You should have inputs there. Have some plugin that simulates this?

  • What do you mean, Sergio, I don’t understand.

  • What you hope to get from $(selected).val(); ?

  • I hope to bring the checked items.

1 answer

2


According to http://bootsnipp.com/snippets/featured/checked-list-group, follow example right 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>

inserir a descrição da imagem aqui

Online Example: Jsfiddle


Part of Sending 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) {
            }
});

Method of Controller Registration

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

inserir a descrição da imagem aqui

  • A doubt. I made an Alert like this: alet(checkedItems); and came no Alert, in the example posted by Maria.

  • alert(JSON.stringify(checkedItems, null, '\t')); if made like this? does a thing also that is good to check javascript errors install firebug in your browser and there before Alert put a console.log(checkedItems). Even if there are other errors on the page it will identify ...

  • I cannot pass to my controller the items checked by the example posted by Maria.

  • No errors of js

  • There was a mistake yes in the past, the event had to be informed, but now I’ve put in your pattern and note that it’s a <button do type='button'></button>

  • I made an edit and posted my controller.

Show 1 more comment

Browser other questions tagged

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