检查单选按钮和字段以启用链接

时间:2011-02-04 00:04:41

标签: javascript jquery validation forms

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

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

$("#link").click(function(e) {
    if ($('input[name=pic]:checked').val() && $('#email').val() && $('#comment').val()) lightbox();
    else e.preventDefault();
});

答案 2 :(得分:0)

function checklink() {
    if ($('[name=pic]').val()) && $('#email').val() && $('#comment').val()) {
        $('#linkId').hide();
    } else {
       $('#linkId').show()
}

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

修改:根据@fehergeri评论

修复了停用问题