jQuery: Run custom function 'if' if statement is false
The custom function formdvalidate should run after else but it doesn't. How can I trigger it to run? What I like to accomplish here is to check the text-fields of a form. If there are less then 3 characters its show the user some text. If the input is more then 3 it submits the form.
--I was thinking to wrong way, this works better.
$('#submit').click(formdvalidate);
The function
function formdvalidate(){
$(".form-sel").each(function(){
var n = $(this).closest('.contain-form').find('.custom:first').val().length;
if ($('option:selected', this).val() === 'custom' && n < 3) {
开发者_Go百科 $(this).closest('.contain-form').find('.alert-short:first').show();
}else{
$('#poll').submit();
}
});
}
- A function assigned as a click handler via
.click()
takes a jQuery event object as its first param--you named that param the same as your function formdvalidate === true
will never evaluate to true asformdvalidate
is a function in the global scope, and a jQuery event object in theclick()
scope as per item 1- In your
formdvalidate
function, your return is inside of the.each()
function, soformdvalidate
never actually returns anything.
I'm not sure what you're really after or what your page looks like, but based on your comment to Slava Yanson, my best guess for you is below (although there are still things I am unsure of...)
$( '#submit' ).click( function( e )
{
if( formdvalidate() === true)
{
$( '#poll' ).submit();
}
e.preventDefault();
} );
function formdvalidate()
{
var returnValue;
$( '.form-sel' ).each( function()
{
var $containForm = $( this ).closest( '.contain-form' ),
$alertShortFirst = $containForm.find( '.alert-short:first' ),
n = $containForm.find( '.custom:first' ).val().length;
if( $( 'option:selected', this ).val() === 'custom' && n < 3 )
{
$alertShortFirst.show();
returnValue = false;
}
else
{
$alertShortFirst.hide();
returnValue = true;
}
} );
return returnValue;
}
The formdvalidate
parameter is hiding the formdvalidate
function.
Use better names.
Try
$('#submit').click(function() {
if (formdvalidate() === true) {
$('#poll').submit();
} else {
formdvalidate();
}
});
I don't know if your logic will accomplish what you're trying to though.
On line 2 of your code you are comparing an instance of your function to boolean. That won't validate. Can you provide more information on what you are trying to accomplish?
Your argument "formvalidate" is shadowing your "formvalidate" function. Just rename your argument to something like this:
$('#submit').click(function(do_validate) {
if (do_validate === true) {
$('#poll').submit();
} else {
formdvalidate();
}
});
精彩评论