Skip to content Skip to sidebar Skip to footer

Collect Checkbox Values In Jquery And Post Them On Submit

I've referred to this post: Post array of multiple checkbox values And this jQuery forum post: http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-val

Solution 1:

Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then

<script>

$("#advancedSearchForm").submit(function() {

     var chkbxValues = $(".tehAwesomeCheckboxen").val();
     $("#specialty").val( chkbxValues.join(",") );

});

</script>

EDIT:

I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:

<script>var chkbxValues = newArray();

    $(".tehAwesomeCheckboxen").live("change", function(e){
        var val = $(this).val();

        if( $(this).is(":checked") ) {
            if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
                // Add the value 
                chkbxValues.push(val);
            }
        }
        else {
            // remove the value
            chkbxValues.splice( chkbxValues.indexOf(val), 1 );
        }

        $("#specialty").val( chkbxValues.join(",") );
    });

</script>

This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.

Is this more in line with what you're trying to do?

P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.

Solution 2:

I ended up solving it using PHP arrays rather than jQuery:

<inputtype="checkbox"name="chk[]"id="RET"class="chk"value="RET"<?phpecho set_checkbox('chk', 'RET'); ?>/>

I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.

Solution 3:

You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.

However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:

<scripttype="text/javascript">
$("#advancedSearchForm").submit(function() {
 var form = this;
 $(form).find("input[name=specialty]").val((function() {
  return $("input:checkbox",form).map(function() {
   return $(this).attr("name");
  }).get().join();
 })());
});
</script>

Or even better, calculate the value first:

<scripttype="text/javascript">
$("#advancedSearchForm").submit(function() {
 var form = this;
 var value = $("input:checkbox",form).map(function() {
   return $(this).attr("name");
 }).get().join();
 $(form).find("input[name=specialty]").val(value);
});
</script>

Post a Comment for "Collect Checkbox Values In Jquery And Post Them On Submit"