1

I'm attempting to place the values of checked checkboxes into an array so I will be able to use these values to build a custom SQL statement to be run against a database.

Think of it as a Select Query Builder for non-tech people.

I can't seem to place these values into an array though. Any tips would be welcome.

Sample HTML:

<input type="checkbox" value="cat">Cat<br>
<input type="checkbox" value="dog">Dog<br>
<input type="checkbox" value="turtle">Turtle<br>
<input type="text" id="demo" hidden>
<input id="button" type="submit" value="Submit">

Sample JQuery:

$(document).ready(function(){
    $("#button").click(function(){
        var i;
        var x = $(":checkbox:checked").toArray()
        for (i = 0; I < x.length; i++) {
            $("#demo").append(x.[i] + ", ");
        }
    });
});
isherwood
  • 58,414
  • 16
  • 114
  • 157
Diogenes
  • 35
  • 1
  • 8

1 Answers1

0

Use .map() in jquery. Translate all items in an array or object to new array of items.

var x = $("input[type=checkbox]:checked").map(function() {
     return this.value;
}).get();
$("#demo").val(x.join(", "));

Sample jsfiddle

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49