Condition a link to redirect

0

How can a link be conditioned?

that is, if a condition is met that is just redirected to the URL of the link, otherwise it will not.

if ($(this).is(":checked")) {
console.log("SI deberia funcionar el link");
}else{
console.log("NO deberia funcionar el link");

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/miLink"> link
<input type="checkbox" id="miCheck">

In this case that I pose, the check mark would be the condition so that the link can be enabled

    
asked by hubman 14.04.2017 в 17:57
source

2 answers

1

From what I see, you want to disable a link depending on the status of the checkbox. There are several ways, one is removing the href from the link:

if ($('#miCheck').is(":checked")) {
  $('#link').attr('href', 'https://es.stackoverflow.com');
} else {
  $('#link').attr('href', 'javascript:void(0)');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://es.stackoverflow.com" id="link" disabled>Inicio</a>
<input type="checkbox" id="miCheck" checked>

Another way is to use a class that simulates the link is disabled:

$('#miCheck').on('change', function () {
  if ($(this).is(":checked")) {
    $('#link').removeClass('disabled');
  } else {
    $('#link').addClass('disabled');
  }
});

/* Para que evalúe al cargar el documento */
if ($('#miCheck').is(":checked")) {
  $('#link').removeClass('disabled');
} else {
  $('#link').addClass('disabled');
}
.disabled {
  color: #ddd;
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://es.stackoverflow.com" id="link" disabled>Inicio</a>
<input type="checkbox" id="miCheck">
    
answered by 14.04.2017 / 18:05
source
1

You can do the validation in this way.

$('#miCheck').on('click', function(){
if ($(this).is(":checked")) {
 $('a').show()
}else{
  $('a').hide()
console.log("NO deberia funcionar el link");

}

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link" style="display:none" href="/miLink"> link </a>
<input type="checkbox" id="miCheck">
    
answered by 14.04.2017 в 18:17