开发者

How to re-populate hidden CSV field on form submit using jQuery

开发者 https://www.devze.com 2023-01-27 02:38 出处:网络
<form> <input type=\"checkbox\" id=\"01\" name=\"01\" /> <input type=\"checkbox\" id=\"02\" name=\"02\" />
<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 abo开发者_Python百科ve; 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.


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.

0

精彩评论

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