1
<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>

I have the form above; checkboxes 01 and 03 are ticked when the page has finished loading using the code below.

I now need to ensure that when the value of the checkboxes change, so too does the hidden CSV field (though this could perhaps be done when the form submits?). 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');
}

Some kind person gave me this code in my previous question:

$(':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(',');
    }
});

Which I think is close, but isn't quite there yet. Any further help on this would be great, thanks in advance.

1
  • Keep in mind, that ids that start with a digit are invalid and may lead to problems. Commented Nov 25, 2010 at 11:59

1 Answer 1

3

You can build a CSV from element attributes concisely using .map:

$(":checkbox").change(function() {
    var csv = $(":checkbox:checked").map(function() {
        return this.id;
    }).get().join(",");
    alert(csv);
    $("input:hidden").val(csv);
});

Demo: http://jsfiddle.net/karim79/tqAnX/2/

As a side-note, element IDs should not begin with numbers.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 - good to note that the ID number restriction is HTML4 specific, not HTML5 :)
That is perfect, and beautifully concise - thank you. Works with the first block of code in my question (to actually populate the checkboxes), but only when I place it before it. Any idea why that is?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.