mercredi 20 décembre 2017

Disable unchecked check boxes in selected div element using jquery

I am creating check boxes dynamically using jquery. I want to disable unchecked check boxes as shown in the snippet,but i want to disable the check boxes only in their respective div elements and not in the other div elements which is what causing issue now.

I have written the code to disable/enable checkboxes based on their respective div tags and i have commented it as it is throwing error if enabled.

$($(".checkbox").eq(id).":checkbox[name='radio']:not(:checked)").prop('disabled', true);

Problem explanation : Here i am creating two div tags dynamically inside which check boxes are also created with same name. So if i check on checkbox in first div other checkbox gets disabled and other div tag gets created which works as expected. but if i check any option in second div tag other option in second div tag doesn't get disabled and also if i uncheck the checked option in first div tag both options get disabled in first div tag. I guess this is because all checkboxes have same names.

How can we disable checkboxes only in their respective div tags. I tried below code but didn't work

$($(".checkbox").eq(1).":checkbox[name='radio']:not(:checked)").prop('disabled', true);

Below snippet explains the problem more appropriately Please help me.

function checkdiv(id, val) {
  if ($(":checkbox[name='radio']:checked").length == 1)
    $(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
  else
    $(":checkbox[name='radio']:not(:checked)").prop('disabled', false);

  var diva = Number(id) + 1;
  var divb = Number(id) + 1;
  //if(id.length != 0){
  if (val.checked == true) {
    if (diva < 2 && divb < 2) {
      creatediv('maindiv')
    }
  }
  //    }
  else {
    var diva = Number(id) + 1;
    var divb = Number(id) + 1;

    $("#" + diva).remove();
    $(".divot").eq(divb).remove();

  }
}

function creatediv(main) {
  var divid = $(".divin").length;
  var divid1 = $(".divot").length;


  var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";

  $('#' + main).append(div);



  loadval(divid)

}

function loadval(div) {

  var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
  $("#" + div).append(div1)
}
<script src="http://ift.tt/1qRgvOJ"></script>

<body onload="creatediv('maindiv')">
  <div class="container">
    <div class="form-group row" id="maindiv">

    </div>
  </div>
</body>



Aucun commentaire:

Enregistrer un commentaire