如果复选框被选中,只允许链接被点击

Only allow a link to be clickable if checkbox is selected

本文关键字:链接 许链接 复选框 如果      更新时间:2023-09-26

我试图设置一个按钮/链接,只有在选中复选框时才能单击。到目前为止我的代码是

<form>
<input type="checkbox" name="agreeCheckbox" value="agreeCheckbox">By clicking this you agree that you are adding a subscription/recurring product to your order<br>
</form>
<a href="exmaple.com">This link is only clickable if checkbox is checked</a>

我假设我将不得不在javascript中这样做,虽然我是一个初学者,当它涉及到javascript。由于

这段代码向元素添加了一些id属性,以便为Javascript提供一些钩子。它隐藏并阻止锚的默认动作,直到复选框被点击。

<form>
<input id="agreement" type="checkbox" name="agreeCheckbox" value="agreeCheckbox">By clicking this you agree that you are adding a subscription/recurring product to your order<br>
</form>
<a href="exmaple.com" id="link">This link is only clickable if checkbox is checked</a>
Javascript

var chk = document.getElementById("agreement");
var anchor = document.getElementById("link");
anchor.style.display = "none";
anchor.onclick = function(e){
  e.preventDefault();
}
chk.onclick = function(){
    if(chk.checked){
        anchor.style.display = "inline";
      anchor.onclick = "";
    }
}

工作示例

http://jsfiddle.net/zVCD7/

这是一个使用纯javascript的简单方法,使用我添加的一些ID属性作为javascript document.getElementById()函数的钩子。

HTML:

<form>
    <p><input type="checkbox" id="agreeCheckbox" name="agreeCheckbox" value="agreeCheckbox" onchange="toggleLink(this);">By clicking this you agree that you are adding a subscription/recurring product to your order</p>
</form>
<p><a href="exmaple.com" id="agreeLink" style="display:none;">This link is only clickable if checkbox is checked</a></p>

Javascript:

function toggleLink(checkBox)
{
    var link = document.getElementById("agreeLink");
    if (checkBox.checked)
        link.style.display = "inline";
    else
        link.style.display = "none";
}

工作示例

<input type="checkbox" name="agreeCheckbox" id="agreeCheckbox" value="agreeCheckbox">By clicking this you agree that you are adding a subscription/recurring product to your order<br>
<div id="mycheck">
<a href="exmaple.com">This link is only clickable if checkbox is checked</a>
</div>

var check= document.getElementById('agreeCheckbox');
  if (check.checked){
    document.getElementById('mycheck').style.display='block';
  }
else{
 document.getElementById('mycheck').style.display='none';
}

有多种方法可以完成此操作。大多数较新的方法可能涉及jQuery。

首先,包含jQuery (Google works):

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

然后,创建链接,而不是链接:

<div id="mylink">This link is only clickable if checkbox is checked</div>

下一步,如果框被点击,使其可点击:

<script type="text/javascript">
$("input[name = 'agreeCheckbox']").click(function(){
  $("#mylink").html('<a href="exmaple.com">This link is only clickable if checkbox is checked</a>');
});
</script>