JQuery Save checkbox values ​​in div

How can I get this list of checkboxes to add to the div before their selected state, so if they are selected, they should be added to the div if they are not removed from the list if they are not selected.

<div id="selected-people"></div>

<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />

Is it possible to extract the identifier name as a stored value, so the id value will be added to the div instead of the value - the value must have a number so that it is added to the database for later use.

I looked here, there is one with checkboxes and a text box, I changed some parts around, didn't even work.

function storeuser() 
{         
    var users = [];

    $('input[type=checkbox]:checked').each(function() 
    {
        users.push($(this).val());
    });

    $('#selected-people').html(users)
}

$(function() 
{
    $('input[type=checkbox]').click(storeuser);
    storeuser();
});
+3
source share
4 answers

So, do you want the DIV to be updated whenever the checkbox is checked? Does this sound right?

http://jsfiddle.net/HBXvy/

var $checkboxes;

function storeuser() {         
    var users = $checkboxes.map(function() {
        if(this.checked) return this.id;
    }).get().join(',');
    $('#selected-people').html(users); 
}

$(function() {
    $checkboxes = $('input:checkbox').change(storeuser);
});​
+6

, .

$.each($('input'), function(index, value) {
    $('selected-people').append($(value).attr('id'));
});


$(document).ready(function() {
    $.each($('input'), function(index, value) {
         $(value).bind('click', function() {
             $('selected-people').append($(value).attr('id'));
         });
    });
});

. click . , , "change".

+2

Edit:

users.push($(this).val());

at

users.push($(this).attr('id'));
0
source

This is for binding comma-separated values ​​to enter a list of checkboxes

$(".chkboxes").val("1,2,3,4,5,6".split(','));

it will link the checkboxes according to the given value of the string in a separated comma.

0
source

Source: https://habr.com/ru/post/1763375/


All Articles