简体   繁体   中英

HTML form radio button to submit or hide on click with jquery

I am trying to use jquery to either submit or hide depending on the radio button that is clicked. I am submitting the value to mysql. The radio buttons are in a tr. If I include a submit button in the form I can update mysql with the value successfully.

<tr>
    <form name="MyStatusForm" id="MyStatusForm" method="post" action="update.php">
        <td class="statuscolumn">
            <input name='status' type='radio' value='1' />
            <label for="new">New</label>
            <input name='status' type='radio' value='2' />
            <label for="accept">Accept</label>
            <input name='status' type='radio' value='3' />
            <label for="resolve">Resolve</label>
        </td>
    </form>
</tr>

My script looks for the value of the radio button to determine which action to take.

$('input[type=radio]').click(function () {
    var $closestTR = $(this).closest('tr');
    var $closestForm = $(this).closest('form');
    if (this.value == '1') || (this.value == '2') {
        $closestForm.submit();
    }
    if (this.value == '3') {
        var ok = confirm("some message?");
        if (ok == true) {
            $closestTR.hide("slow");
        } else {
            return;
        }
    }
});

The hide works fine. It is only the submit that doesn't work. There is no response when I click the radio button and mysql is not updated.

Thanks for your help

Working Demo

Corrected Markup

HTML

<table>
    <tr>
        <td class="statuscolumn">
            <form>
                <input name='status' type='radio' value='1' />
                <label for="new">New</label>
                <input name='status' type='radio' value='2' />
                <label for="accept">Accept</label>
                <input name='status' type='radio' value='3' />
                <label for="resolve">Resolve</label>
            </form>
        </td>
    </tr>
</table>

js

$('input[type="radio"][name="status"]').click(function () {
    var $closestTR = $(this).parents('tr');
    $closestForm = $(this).parents('form');
    if (($(this).attr('value') == '1') || ($(this).attr('value') == '2')) {
        $closestForm.submit();
    }
    if (this.value == '3') {
        var ok = confirm("some message?");
        console.log(ok);
        if (ok == true) {
            $closestTR.hide();
        } else {
            return;
        }
    }
});

You have a syntax error in your if, should be

if ((this.value == '1') || (this.value == '2'))

Also, don't forget to fix your markup as @adeneo suggested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM