I have a form with a bunch of checkboxes, and a hidden field that contains CSV data. Basically, I need the checkboxes to be ticked based on the value of the hidden field:
<form>
<input type="checkbox" id="01" name="01" />
<input type="checkbox" id="02" name="02" />
<input type="checkbox" id="03" name="03" />
<input type="hidden" value="03,01," />
</form>
So, in the example above checkboxes 01 and 03 need to be ticked when the page has finished loading. I also need to ensure that when the value of the checkboxes changes, so too does the hidden CSV field (though this could perhaps be done when the form submits?).
My limited jQuery knowledge has got me nowhere with this, any help would be much appreciated. (I know that some开发者_开发知识库 of this would be best done server-side, but I have no access to anything but javascript).
The answer below does most of what I want. I think that using the variables created, it should be possible to re-populate the CSV field when the form submits. ie, using selected_ids to add the ids of the checked boxes onto the end of the CSV (if they aren't already present). Can this be done?
var csvValue = $('#csv-input').val();
var selected_ids = csvValue.split(',');
for (var i = 0; i < selected_ids.length; i++)
{
var selected_id = selected_ids[i];
$('#' + selected_id).attr('checked', 'checked');
}
$(':checkbox').bind('change', function(event){
if (this.checked == true){
// add to hidden field
var tempIdStr = $('#cvs-input').val();
// if not in hidden value already
if (tempIdStr.indexOf(this.id) > -1){
tempIdStr += "id,"; // or ", id" depending on how you are seperating the ids
$('#cvs-input').val(tempIdStr);
}
} else {
// remove from hidden field
var tempIds = $('#cvs-input').val().split(',');
var index = tempIds.indexOf(this.id);
if (index > -1){
tempIds.splice(index, 1);
$('#cvs-input').val(tempIds.join(',');
}
});
精彩评论