check radio buttons and fields to enable link

2019-07-20 13:14发布

I have a form with a lot of radio buttons and a couple of text fields. So...

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

and there's a link after the form that will open up a lightbox. I want the link to be enabled only if a radio button is selected and the two fields are filled out. Thanks a lot for your help.

3条回答
Explosion°爆炸
2楼-- · 2019-07-20 13:26
$("#link").click(function(e) {
    if ($('input[name=pic]:checked').val() && $('#email').val() && $('#comment').val()) lightbox();
    else e.preventDefault();
});
查看更多
疯言疯语
3楼-- · 2019-07-20 13:29
function checklink() {
    if ($('[name=pic]').val()) && $('#email').val() && $('#comment').val()) {
        $('#linkId').hide();
    } else {
       $('#linkId').show()
}

then add onchange="checklink()" to your input fields

Edit: fixed disabling as per @fehergeri comment

查看更多
贼婆χ
4楼-- · 2019-07-20 13:41

I think that this should work:

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.");
}


Edited to amend your code:

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.

查看更多
登录 后发表回答