Tony Gred
Tony Gred

Reputation: 15

JS validation when multiple forms are present

Hi I have the following in my code. My issue is when handling multiple forms in the same page how to I adjust the code to pick only the relevant form submit?

The JS activates even when an undesired form also submits.

I tried altering the code to look like something $('input[type=submit, name=deletenow]').click(function() { but surely it seems inaccurate. Please help. Thank you for looking.

$(document).ready(function() {

    $('input[type=submit]').click(function() {

    });

    $('input[type=submit]').confirm({
        msg:'Do you really want to delete this?',
        timeout:3000
    });



});

Upvotes: 0

Views: 86

Answers (2)

thordarson
thordarson

Reputation: 6251

You shouldn't be listening for clicks on your submit buttons as that kills accessibility. Instead you should listen for the submit event on the form itself.

Give your form an ID, and then listen for the submit event using that ID, like so:

<form id="yourForm" method="POST" action="">
    <input type="submit">
</form>

$('#yourForm').submit(function(event){
    event.preventDefault();  // Prevents the form from submitting.
});

The preventDefault method stops the form from submitting. You might want to create some conditions where it's called instead of stopping it every time like my demo does.

Upvotes: 4

nickanor
nickanor

Reputation: 669

<form id="formForEvent" method="POST" action="">
    <input id="submit-Btn" type="submit">
</form> <!--taken from @thordarson answer with additional [id]-->

$('form#formForEvent').on('click', 'input#submit-Btn', function(){
    // your code
    return false;
});

Upvotes: 0

Related Questions