check radio buttons and fields to enable link

2019-07-20 12:48发布

问题:

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.

回答1:

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.



回答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()
}

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

Edit: fixed disabling as per @fehergeri comment