如果选中复选框,则仅允许链接可点击

时间:2013-04-26 19:18:51

标签: javascript html checkbox hyperlink

我正在尝试设置一个只有在选中复选框时才可点击的按钮/链接。所以到目前为止我的代码将是

<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。感谢

4 个答案:

答案 0 :(得分:2)

此代码向元素添加了一些id属性,以便为Javascript提供一些挂钩。在单击复选框之前,它会隐藏并阻止锚点的默认操作。

<强> HTML

<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/

答案 1 :(得分:2)

这是一种使用纯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";
}

<强> WORKING EXAMPLE

答案 2 :(得分:0)

<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';
}

答案 3 :(得分:0)

您可以通过多种方式实现这一目标。大多数较新的方法可能涉及jQuery。

首先,包括jQuery(Google的作品):

<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>