cartmander
cartmander

Reputation: 182

How to get the checked checkboxes values with ID in javascript

I'm currently trying to get the values of checked checkboxes. These checkboxes have unique IDs because they are defined on a modal box.

<input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name-$row[asset_ID]' value = 'SMB'> SMB
<input type = 'button' id = 'editAssetColumn' value = 'Submit'>

And here, I'm testing if I'm retrieving them but unfortunately, I cannot.

$("button#editAssetColumn").click( function() {
    var edit_id = $(this).attr('id');
    var name = $("input#audience_Name:checked-"+edit_id).val();
    $('input#audience_Name:checked-'+edit_id).each(function() {
        alert("Success!");
    }); 
});

I believe it's the syntax... Thanks in advance!

Upvotes: 0

Views: 2213

Answers (3)

Yann
Yann

Reputation: 604

Here you go. I'm using console.log() because I'm not a fan of getting a bazillion popups… But other than that, it's the same thing.

$("#editAssetColumn").on("click", function() {
  $('input:checkbox:checked').each(function() {
    console.log($(this).val());
  });
});

Upvotes: 0

Mujtaba Haider
Mujtaba Haider

Reputation: 1650

Here is html and js, there were multiple problems in your code, JSFIDDLE here

HTML

<input type = 'checkbox' id = 'audience_Name[]-$row[1]' class="audience_Name" value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name[]-$row[2]' class="audience_Name" value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name[]-$row[3]' class="audience_Name" value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name[]-$row[4]' class="audience_Name"  value = 'SMB'> SMB
<input type = 'checkbox' id = 'audience_Name[]-$row[5]'  class="audience_Name"  value = 'SMB'> SMB
<input type = 'button' id = 'editAssetColumn' value = 'Submit'>

JS

$(document).ready(function(){
  $("#editAssetColumn").click( function() {
    console.log("here");
    $('.audience_Name:checked').each(function() {
        console.log("asdfsf");
    }); 
  });
});

Upvotes: 1

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

Your id is in the wrong format. it should be "input#audience_Name-" + edit_id + ":checked". since you are using the jQuery :checked selector.

Upvotes: 0

Related Questions