1

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

<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

4 回答 4

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/

于 2013-04-26T19:31:42.847 回答
2

这是一种使用纯 javascript 的简单方法,使用我添加的一些 ID 属性作为 javascriptdocument.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";
}

工作示例

于 2013-04-26T19:44:38.553 回答
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';
}
于 2013-04-26T19:26:48.447 回答
0

有多种方法可以实现这一点。大多数较新的方法可能会涉及 jQuery。

首先,包括 jQuery(谷歌作品):

<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>
于 2013-04-26T19:31:51.683 回答