简体   繁体   中英

Form not submitting when JavaScript validated

I have a form with a dropdown that gets validated, the validation works fine but form won't submit if user selects any option other than the default.

I created a jsfiddle of the current code in an easier to read format.

Why isn't my form submitting?

JavaScript

$('#btncheck').click(function () {
    if ($("#mySelect ")[0].selectedIndex <= 0) {
        alert("Please select a tank from the menu!");
        return false;
    } else {
        return true;
        form.submit();
    }
});

Anything after return won't fire:

return true;
form.submit(); 

It's because you have a return true statement above form.submit(); You need to switch the order of these.

$('#btncheck').click(function(){
    if ($("#mySelect")[0].selectedIndex <= 0) {
         alert("Please select a tank from the menu!");
         return false;
    }
    form.submit(); 
    return true;
});

(I've also cleaned up your code a little.)


I've edited your JSFiddle, and come up with a working example. http://jsfiddle.net/36JZL/44/ You can see that the part of the code that submits the form is being reached when the alert box pops up.


To answer your last comment, I've updated the JSFiddle. http://jsfiddle.net/36JZL/46/ . This changes the background color of the drop-down and gives an error message beneath it.

   $(document).ready(function() {
$('#btncheck').click(function(){
     if ($("#mySelect ")[0].selectedIndex <= 0) {
         alert("Please select a tank from the menu!");
                return false;
                }
    else {
        //return true;
        $('form').submit(); 
    }
});
});

ps add action tag (eg action='server-side.php') in form, otherwise form will be submitted/processed to/on same page (maybe you want it, don't know) and method (i guess that you don't want default - GET)

Return is the end point of any function !

Anything placed after return won't execute.

I suggest you use a step by step debugger with breakpoints, here's a guide for chrome dev tools https://developers.google.com/chrome-developer-tools/docs/javascript-debugging

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