【问题标题】:check radio buttons and fields to enable link检查单选按钮和字段以启用链接
【发布时间】:2011-06-21 01:29:54
【问题描述】:

我有一个包含很多单选按钮和几个文本字段的表单。所以...

<input type="radio" name="pic" id="pic" value="val1">
<input type="radio" name="pic" id="pic" value="val2">
<input type="radio" name="pic" id="pic" value="val3">

<input type="text" name="email" id="email" value="">
<input type="text" name="comment" id="comment" value="">

表单后面有一个链接,可以打开一个灯箱。我希望仅在选择单选按钮并填写两个字段时才启用链接。非常感谢你的帮助。

【问题讨论】:

标签: javascript jquery validation forms


【解决方案1】:

我认为这应该可行:

if ($('input:radio[name=pic]:checked').length && $('#email').val().length && $('#comment').val().length) {
    /* activate the lightbox link */
}

else {
    alert("Please ensure you've selected one of the radio buttons, and filled out the text-fields.");
}


已编辑以修改您的代码:

html:

<form action="#" method="post">
    <input type="radio" name="pic" id="pic" value="val1">
    <input type="radio" name="pic" id="pic" value="val2">
    <input type="radio" name="pic" id="pic" value="val3">

    <input type="text" name="email" id="email" value="">
    <input type="text" name="comment" id="comment" value="">
    <input type="submit" value="submit" />
</form>

jQuery:

$('form').submit(

function() {
    if ($('input:radio[name=pic]:checked').length && $('#email').val().length && $('#comment').val().length) { /* activate the lightbox link */
    }
    else {
        alert("Please ensure you've selected one of the radio buttons, and filled out the text-fields.");
    }
    return false;
});

JS Fiddle demo.

【讨论】:

  • 这有点复杂吧?
  • @fehergeri,是的。嗯,也许…​​…来晚了,我累了……?我......现在应该停止说话了,不是吗?
【解决方案2】:
$("#link").click(function(e) {
    if ($('input[name=pic]:checked').val() && $('#email').val() && $('#comment').val()) lightbox();
    else e.preventDefault();
});

【讨论】:

    【解决方案3】:
    function checklink() {
        if ($('[name=pic]').val()) && $('#email').val() && $('#comment').val()) {
            $('#linkId').hide();
        } else {
           $('#linkId').show()
    }
    

    然后将onchange="checklink()" 添加到您的输入字段

    编辑:根据@fehergeri 评论修复禁用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 2011-11-29
      • 1970-01-01
      • 2012-10-17
      • 2018-08-12
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多