7

Submit a form based on the javascript event

 2 years ago
source link: https://www.codesd.com/item/submit-a-form-based-on-the-javascript-event.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Submit a form based on the javascript event

advertisements

What I want is to be able to submit a form when ever a user presses some key like tab or enter (i.e. that will case him to lose focus) also clicking outside of the text field should trigger a submit. However when ever he click on the cancel button it should prevent the submit ion

html structure look like this

<form id="form">
  <input id="text" onblur="$(this).closest('form').submit();">
  <a id"submit">submit</a>
  <a id"cancel">cancel</a>
</form>

Currently what happens is that when a user presses enter a form is submitted twice and it should be submitted only once. When he presses a cancel a form is submitted and cancelled right after that.

Does anyone have any idea how can I write some javascript code that can accomplish this behaviour (the idea for is take form the jira in-line edit mode and I am trying to construct something in similar manner)


I'm going to provide you with another you could approach this by using jQuery and it's .change() event handler. This way when the user clicks off of the input element, it'll trigger the .change() event and you can submit a form within it's callback function. If the user cancels then you can handle that event normally, same with the submit button click.

The Form:

<form id="form">
  <input id="text">
  <a id="cancel">cancel</a>
  <a id="submit">submit</a>
</form>

The Javascript (jQuery):

$(document).ready(function(){
    $('#submit').click(function(e){
        e.preventDefault();
        //submit the form
        console.log('form submitted by button click')
    });
    $('#cancel').click(function(e) {
        e.preventDefault();
        //close form?
        console.log('cancelled form');
    });

    $('#text').change(function(){
        //submit the form
        console.log('form submitted, maybe hide form now?');
    });
});

The jsFiddle.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK