Malaiselvan
Malaiselvan

Reputation: 1125

How to get the selected checkbox values on a button click?

How to get the selected checkbox values inside the list view on a button click?

I am building the list items dynamically using jQuery append.

This is the jQuery code which creates the list items... The obj_address_list is an array of objects which each object will have name, alias, id and mobile. The value of the checkbox would be like 'Name'

$.each(obj_address_list, function(ctr, obj) {
  $('#ul_address_list').append('<li data-icon="false">' +
    '<a href="#" class="add-container">' +
      '<label class="add-container" data-corners="false">' +
        '<input name="chk_address" id="chk_address" type="checkbox" value="'+obj.name+'<'+obj.alias+'-'+obj.id+'>'+'" />' +
        '<label class="lbl_add-container">' +
          '<h3>'+obj.name+'</h3>' +
          '<p>'+obj.mobile+'</p></div>' +
        '</label>' +
      '</label>' +
    '</a>' +
  '</li>');
});
$("input[name=chk_address]").checkboxradio();
$('#ul_address_list').listview('refresh');

Find below the screen after appending.

enter image description here

When the 'Send' button is clicked I need to capture all the selected checkbox values and pass it to an another page.

Following is the code I am trying to use on tapping the send button. The id of the button is 'a_send-sms' and id of the checkbox is 'chk_address'. But this doesnt seem to be working.

$("#a_send-sms").on("tap",function(e){
  e.preventDefault();
  var selected = new Array();
  $('#chk_address input:checked').each(function() {
    alert('inside');
    selected.push($(this).attr('value'));
  });
  console.log(selected);
});

What am I missing?

Upvotes: 1

Views: 4554

Answers (2)

Omar
Omar

Reputation: 31732

As @Sergio said, you should not use the same id for several elements. Also, your selector $('#chk_address input:checked') is wrong. jQuery will consider chk_address as a parent and look for children elements checked input.

$("#a_send-sms").on("tap",function(e){
  e.preventDefault();
  var selected = new Array();
  $('ul input:checked').each(function() { // or listview id
    alert('inside');
    selected.push($(this).val()); // instead of .attr("value")
  });
  console.log(selected);
});

Upvotes: 2

Sergio
Sergio

Reputation: 28837

You cannot have multiple ID's, ID's must be unique. Give a class to those checkboxes and then iterate them:

$('input.chk_address:checked')
        ^

So try:

$("#a_send-sms").on("tap",function(e){
  e.preventDefault();
  var selected = new Array();
  $('input.chk_address:checked').each(function() {
    alert('inside');
    selected.push(this.value);
  });
  console.log(selected);
});

Upvotes: 2

Related Questions