max
max

Reputation: 328

Unexpected JavaScript (jQuery) Behavior (Function call, rather than Form submit)

Okay, I don't get this.

I have a specific type of form-declaration, jQuery will always process the Form Data and sends an Ajax-Request, but inside the form, I have Buttons, once for Form-Submission (Ajax) and once for calling specific Functions. Like so:

<button data-click="regenUSID">Regenerate</button>

Both called like so in jQuery:

$(function() {
    $('form.ajax').submit(function(event) {
        event.preventDefault();
        var data = $(this).serializeArray();
        // do stuff with data       
    });

    $('[data-click]').click(function(event) {
        // prevents form submit
        event.preventDefault();
        // calls defined function and passes element that got clicked on
        window[$(this).attr('data-click')](this);
    });
});

Now the strange thing, if I click the data-click Button, it works, if I click the intended submit-button, it also works, but if I have a normal input text field inside the form and press return, to "submit" the form, it does whatever the first button does in the form, conclusion, if the form-submit button is before the data-click button, everything works just fine, but if the data-click button is before the submit button (wich it is!), the data-click function will be called.

One way to fix this, is to start the form with a hidden submit button, although that ruins the HTML.

All in all, it can look like this:

<form class="ajax" action="/formhandler.php?register" method="POST" role="form">
    <div class="usidrecommendation">
        <?php $usid = Server::generateUnusedUSID(); ?>
        <h1 class="text-center"><?php echo $usid; ?></h1>
    </div>
    <button data-click="regenUSID">Regenerate</button>

    <input type="password" name="password" id="password" placeholder="enter Password here">

    <button class="btn btn-primary btn-block btn-submit">Check data</button>
</form>

<script>

function regenUSID(from) {
    // do stuff
    console.log(from);
}

$(function() {
    $('form.ajax').submit(function(event) {
        event.preventDefault();
        var data = $(this).serializeArray();
        // do stuff with data
    });

    $('[data-click]').click(function(event) {
        // prevents form submit
        event.preventDefault();
        // calls defined function and passes element that got clicked on
        window[$(this).attr('data-click')](this);
    })
});
</script>

Note that every form with the class ajax, should never be submitted "as is", it always has to do a ajax-submission and goes through the JavaScript. The client always has JavaScript enabled, don't worry about that.

Upvotes: 2

Views: 204

Answers (1)

Victory
Victory

Reputation: 5890

The default type for a button is submit so when you press enter in a text box its like clicking the first button. Try:

 <button data-click="regenUSID" type="button">Regenerate</button>

Upvotes: 3

Related Questions