angel1108
angel1108

Reputation: 333

get checkbox attribute using javascript (array)

Hello guys i want to get the attribute of my checkbox. The checkbox was an array so i want to get the attribute of the checked checkboxes and put it on the textbox anf separate it with comma.

Here's my php/html

$query = $db->select('owners_information',array('*'),$con);

foreach($query as $q){
     //echo $q['lastname'];        
      $output .= '
      <tr>
        <td>'.$q["firstname"].'</td>
        <td>'.$q["middlename"].'</td>
        <td>'.$q["lastname"].'</td>
        <td>'.$q["land_area"].'</td>
        <td><input type="text" value="'.$q["OCPC_ID"].'" name="ocid[]">
        <input type="checkbox" value="'.$q["land_area"].'" name="checkval[]" attr="'.$q["OCPC_ID"].'"></td>
      </tr>
      ';

  }
if($query > 0){
    echo '<input type="text" name="textval" id="textval">';
    echo '<br><input type="text" name="ocpc_id" id="ocpc_id">';
    echo '<input type="button" name="merge" id="merge" value="Merge" onclick="mergeFunc()">';
    echo '<input type="button" name="addNew" id="addNew" value="Add New RPU" onclick="addMerge()" style="display:none;">';
    echo $output;
  }else{
    echo "No data found";
  }

And here's my javascript

function mergeFunc() {

var checkboxes = document.getElementsByName('checkval[]');
var cd = document.getElementsByName("checkval[]");

var val_id = "";
for (var l=0, n=cd.length;l<n;l++) 
{
  if (cd[l].checked) 
  {
    val_id += ","+cd[l].attr;
  }
}
if (val_id) val_id = val_id.substring(1);

alert(val_id);


var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
  if (checkboxes[i].checked) 
  {
      vals += ","+checkboxes[i].value;
  }
}
if (vals) vals = vals.substring(1);


$('#ocpc_id').val(val_id);
$('#textval').val(vals);
$('#merge').hide();
$('#addNew').show();
} 

i want to get the attribute of the checkbox named checkval[]. I want to get what's inside the attr array. I hope you could help me guys.

Upvotes: 0

Views: 1027

Answers (2)

angel1108
angel1108

Reputation: 333

var val_id = "";
for (var l=0, n=cd.length;l<n;l++) 
{
  if (cd[l].checked) 
  {
    val_id += ","+cd[l].getAttribute("attr");
  }
}
if (val_id) val_id = val_id.substring(1);

I've change val_id += ","+cd[l].attr; to val_id += ","+cd[l].getAttribute("attr");

Thanks for your time guys.

Upvotes: 0

Prasanna Venkatesh
Prasanna Venkatesh

Reputation: 402

Try this

  document.getElementById('btn').addEventListener('click',function(){
    var checkboxes = document.getElementsByName('checkval[]');
  var input = document.getElementsByName('ocid[]');
  var checkval = '';
  var checkid = '';
  for(var i=0;i<checkboxes.length;i++) {
    if(checkboxes[i].checked){
      i==0 ? checkval += checkboxes[i].value : checkval += ","+checkboxes[i].value;
      i==0 ? checkid += input[i].value : checkid += ","+input[i].value;
    }
  }
  console.log(checkval+" "+checkid);
});

See the demo

Upvotes: 1

Related Questions