开发者

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if 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 id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.

I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.

function storeuser() 
{         
    var users = [];

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

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

$(funct开发者_StackOverflowion() 
{
    $('input[type=checkbox]').click(storeuser);
    storeuser();
});


So you want to keep the DIV updated whenever a checkbox is clicked? That 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);
});​


Supposing you only have these input controls on page I can write following code.

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

Edited Due to More Description


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

Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.


Change:

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

to:

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


This is for to bind the comma seperated values to input checkbox list

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

it will bind checkboxes according to given string value in comma seperated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜