reyjoel reyjoel - 4 months ago 23
Javascript Question

How to disable the link if the checkbox is unchecked

How can I disable the link(delete and view) if the checkbox is unchecked.

This is my code

<table><form>
<tr>
<th></th>
<th style="width:100px;"><center>Last Name</center></th>
<th style="width:100px;"><center>First Name</center></th>
<th style="width:auto;"><center>Email</center></th>
<th style="width:100px;"><center>Birthday</center></th>
<th style="width:auto;"><center>Action</center></th>
</tr>
<?php
while($row= mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" id=\"box\">";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['bdate']."</td>";
echo "";
echo "<td><center>";
echo "<a href=\"delete.php?id=".$row['id']."\" style=\"text-decoration:none\" class=\"btn\" id=\"delete\">DELETE</a> ";
echo "<a href=\"personal_information.php?id=".$row['id']."\" style=\"text-decoration:none\" class=\"btn\" id=\"view\">VIEW</a> ";
echo "</td></center></td>";
echo "</tr>";

}
?>
</form></table>


Here is my jQuery script(example if I want to disable VIEW link only)

<script>
jQuery('#box').click(function () {
//check if checkbox is checked
if (jQuery(this).is(':checked')) {

jQuery('#view').removeAttr('disabled'); //enable input

} else {
jQuery('#view').attr('disabled', true); //disable input
}
});
</script>


I want to disable the each view and delete per row if the checkbox is uncheck how can I do it? or my jQuery is wrong? Can you give me an example for checkall box

Leo Leo
Answer

Anchors can't not be disabled only form-related elements can be disabled (input, button, textarea, etc.) What you should do is either remove the href attribute or hide the anchor element...

$(function() {
  $("#chkRemove").change(function() {
    if ($(this).is(":checked")) {
      $("a").attr("href", "javascript:void(0)");
    } else {
      $("a").each(function(idx, element) {
        $(element).attr("href", $(element).data("link"));
      });
    }
  });
  
  $("#chkHide").change(function() {
    if ($(this).is(":checked")) {
      $("a").hide();
    } else {
      $("a").show();
    }
  });
});
.links {
  padding: 20px 0;
}
.links a {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div>
  <input id="chkRemove" type="checkbox" />Remove href attribute
</div>
<div>
  <input id="chkHide" type="checkbox" />Hide anchors
</div>

<div class="links">
  <a href="http://google.com" data-link="http://google.com">Google Link</a>

  <a href="http://stackoverflow.com" data-link="http://stackoverflow.com">Stackoverflow Link</a>
</div>

Also, as a side note. Never use the attr function to handle the state of the checkbox or a radio button. Always use the prop function instead

$(selector).prop("checked", true);