How to disable the form submit before it is checke

2019-06-06 13:51发布

I have a form and try to disable post it if radios not selected:

function checkForm(obj){
            var return_value = true;
            var error_msg = 'Some text: '+'\n';

            $("input[type='radio']:not(:checked)").each(function() {
                error_msg += $(this).next().text() + ", ";
            });

            if(!return_value)
                alert(error_msg);

            return return_value;
        }

Form:

<form name="test1" method="post" action="result.php" onsubmit="return checkForm(this);">
    <span id="q2"><h4>My question</h4></span>

    <ul>

    <li><input type="radio" name="answer[2]" value="5" />a1</li>

    <li><input type="radio" name="answer[2]" value="6" />a2</li>

    <li><input type="radio" name="answer[2]" value="7" />a3</li>
    <li><input type="radio" name="answer[2]" value="8" />a4</li>
    </ul>
    </div>
    <div><input type="submit" value="Send!" name="submit" class="button" id="start" /></div>
</form>

But no alert shows and the form is submitted.

标签: jquery submit
2条回答
聊天终结者
2楼-- · 2019-06-06 14:07

you can try this out

$('form[name=test1]').submit(function(){                 
        var return_value = false;             
        var error_msg = 'Some text: '+'\n';  
         $("input[type='radio']").each(function() { 
             if ($(this).attr('checked')){
                 return_value = true; 

             } else {
                 error_msg += $(this).next().text() + ", "; 
             }
              });  

        if(!return_value)                 
                alert(error_msg);              

        return return_value;         
            } );

and in html remove onsubmit function

查看更多
倾城 Initia
3楼-- · 2019-06-06 14:29

You should set the return_value to false if the radio buttons are not checked, because the initial value is true.

查看更多
登录 后发表回答