Kledi
Kledi

Reputation: 23

Get multiple checkbox values with javascript

I have this form which i submit using ajax and jquery , well, i have this multiple checkbox from which i get some values.

Now i am doing an error here since the values of the checkbox are not being posted in the database.. Here is the html/php part :

  while($row = mysql_fetch_assoc( $result )) {
    echo '<input type="checkbox" value="'.$row['regione'].'" id="regioni_gestite_ag" name="regioni_gestite_ag[]">' . $row['regione'] . '<br>';
    }

This is how i get it with javascript:

var js_regioni_gestite_ag = $('input:checkbox[name=regioni_gestite_ag]:checked').val();

If i echo the value, i get undefined... Why is it so?

Upvotes: 0

Views: 4494

Answers (3)

web-nomad
web-nomad

Reputation: 6003

Try this:

var js_regioni_gestite_ag = [];//[name="regioni_gestite_ag[]"]
if($('input[name="regioni_gestite_ag[]"][type=checkbox]:checked').length){
    // check if any checkboxes are checked
    $('input[name="regioni_gestite_ag[]"][type=checkbox]:checked').each(function(o){
        // get their values
        js_regioni_gestite_ag.push($(this).val());
    });
}

// clears all selected checkboxes
function clearSelection() {
    $('input[name="regioni_gestite_ag[]"][type=checkbox]:checked').each(function(o){
        $(this).removeAttr('checked');
    });
}

Hope this helps.

Upvotes: 0

Jon
Jon

Reputation: 437336

Because you are not specifying the name attribute correctly. The selector should be

$('input[name="regioni_gestite_ag[]"]:checkbox:checked')

However, that will still not make everything work because .val() only returns the value of the first matched element (so it will only apply to the first checkbox).

Finally, your PHP code produces multiple elements with the same id attribute, which is illegal HTML and will make random jQuery and/or DOM APIs not work correctly. This should be fixed immediately, perhaps by removing the id entirely?

Update: to get the values of all checkboxes as an array you can use

var values = $.makeArray($('input[name="regioni_gestite_ag[]"]:checkbox:checked')
                          .map(function() { return $(this).val() }));

Upvotes: 2

Try with starts-with selector (^=) , like so:

var js_regioni_gestite_ag = $('input:checkbox[name^=regioni_gestite_ag]:checked').val();

Upvotes: 0

Related Questions