简体   繁体   中英

triggering a form onsubmit using an anchor

I have a form which has a cancel button, a save (submit) button and a save continue link. Now the buttons work and the javascript is called via a function called from the form onsubmit method. This works as expected as does the cancel button. however the save and continue is not working. Follows is a simplified example:

<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this);">
    <input type="text" name="data" value="">
    <a href="" class="admin-link" rel="view-job">&larr; cancel</a>
    <input class="button" type="submit" value="save">
    <a class="button oklink" onclick="document.getElementById('save-form').submit();">ok →</a>
</form>

And the javascript for simplification just alerts ok (the real example has an ajax call to the save-job action):

<script>
    window.jobFormSave = function (aForm) {
        alert( "Ok" );
    }
</script>

So when i click Save button the form is validated, saved and a message is displayed. Clicking on the Ok link however triggers the form submit action (save-job) but i want it to use the jobFormSave function. So I've a few questions:

  1. can this be done while submitting the form data to the function?
  2. can i determine whether i clicked the ok or the save button from within the javascript (or if not within the save-job action function)?
  3. Is there a better way to achieve what seems an everyday thing.

I'm using php 7.2 to handle the forms action functionality and jQuery is available and used for the ajax query in the actual code.

I've kept the code short as mostly it is not relevent to the question but I can provide more code if you guys need it.

Probably you are looking for:

<script>
    window.jobFormSave = function (aForm, action) {
        alert('User '+ action + " form with data "+ JSON.stringify(aForm))
        if (action == 'okayed')
          aForm.submit();
    }
</script>

<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this, 'submitted');">

    <input type="text" name="data" value="">
    <a href="" class="admin-link" rel="view-job">&larr; cancel</a>
    <input class="button" type="submit" value="save">
    <a class="button oklink" href="javascript:{}" onclick="return jobFormSave(document.getElementById('save-form'), 'okayed');">ok →</a>
</form>

Form can be passed as an argument as I did in anchor tag's onclick and then it can be decided to submit at function level based on the action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM