NavyPixel
NavyPixel

Reputation: 260

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();
    }
});

Upvotes: 0

Views: 61

Answers (4)

ktm5124
ktm5124

Reputation: 12123

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.

Upvotes: 1

Hichem ben chaabene
Hichem ben chaabene

Reputation: 145

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

Upvotes: 0

sinisake
sinisake

Reputation: 11318

   $(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(); 
    }
});
});

p.s. add action tag (e.g. 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)

Upvotes: 0

helion3
helion3

Reputation: 37331

Anything after return won't fire:

return true;
form.submit(); 

Upvotes: 4

Related Questions