Unknown developer
Unknown developer

Reputation: 5920

How to get return from event handler

Here is a draft code:

<form action="test.php" method="post">
    <input type="text" id="content">
    <input type="button" name="validate_button" id="validate_button" value="Validate" />
    <input type="submit" name="submit_button" id="submit_button" value="Send" />
</form>

<script>
$('#submit_button').click(function(e) {
    if (!($('#validate_button').click()))
        e.preventDefault();
});

$('#validate_button').click(function() {
    if ($('#content').val() === '')
        return false;
    return true;
});
</script>

I want when clicking submit_button to run the event handler of validate_button and decide for submitting or not the form. Obviously, my condition !($('#validate_button').click()) is not correct since it returns a jQuery object. How may I get return results of the event handler itself?

P.S. Do not suggest to put the condition $('#content').val()==='' inside the first event handler...

Upvotes: 0

Views: 66

Answers (3)

Pete
Pete

Reputation: 58412

Why not create a function and call that in both click handlers:

$('#submit_button').click(function(e){
    if (!validate())
      e.preventDefault();
});

$('#validate_button').click(function(){
    return validate();
});

function validate() {
    if ($('#content').val()==='')
      return false;
    return true;  
}

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Why not not use JavaScript at all?

<input type="text" id="content" required />

Upvotes: 0

Tushar
Tushar

Reputation: 87203

You can create a function and use it as handler to the #validate_button click and it can be called from #submit_button click handler too.

// Function to validate the value of `#content`
// Return false when value is empty, true o.w.
function validate() {
    // Trim the leading and trailing spaces
    // Note: Empty string in JS is falsy
    return $.trim($('#content').val());
}

$('#submit_button').click(function (e) {
    // Other code

    return validate();
});

// Pass the function reference to the click()
$('#validate_button').click(validate);

Upvotes: 0

Related Questions