How to submit the form using javascript with "this"
Asked Answered
C

7

8

Is there any way to submit the current form in which i have the href link like this

<a href="javascript:;" onclick="this.submit();">Save</a>

I want to use same code evrywhere so i can't use any id or class

Cao answered 30/8, 2012 at 4:16 Comment(1)
Why do you want to do this ? It is a good practice to put your code in separate javascript file. Is there any reason you could not separate the markup from the script ?Rosetta
S
15

Submit form using this.form.submit()

i.e in your case it will be like

<a href="#" onclick="this.form.submit();">Save</a>

But it highly recommended to use form name

otherwise if you are comfortable using jquery you can also use jquery closest function

$(field).closest("form").submit();
Scrogan answered 30/8, 2012 at 4:41 Comment(1)
No, it doesn't work: Cannot read property 'submit' of undefinedSoporific
D
1

What you want is:

<a href="javascript:;"onclick="document.forms.<formname>.submit();">Save</a>

Actually it seems to work when <formname> is replaced with the form's id also.

Althoughy I would strongly recommend you research the practice known as Unobtrusive Javascript

Debutant answered 30/8, 2012 at 4:19 Comment(0)
L
1
<a href="" onclick="!function(a){while(a&&a.nodeName!="FORM")a=a.parentNode;if(a)a.submit();}(this);"></a>
Laski answered 30/8, 2012 at 5:0 Comment(1)
The correct code is: <a href="" onclick="!function(a){while(a&&a.nodeName!='FORM')a=a.parentNode;if(a)a.submit();}(this);"></a>.Abysm
R
1

I use this solution for unknown form name:

function submitForm(originator)
{
    var pN=originator.parentNode;
    while (true)
    {
        if (pN&&pN.nodeName=='FORM')
        {
            pN.submit();
            break;
        }
        pN=pN.parentNode;
    }
}

and now on any document's object event we can use this function:

<div onclick="doSomething();submitForm(this)">test</div>
Recoil answered 4/8, 2017 at 6:32 Comment(0)
I
0

Say you have n number of forms on your page. You can submit i+1th form by using:

document.forms[i].submit();

So if you have just one, and want to submit on link click,

document.forms[0].submit();

should be your onclick attribute's value

Istic answered 30/8, 2012 at 4:24 Comment(1)
but then i need to diff code for every href. I have around 30 files and i am replacing the submit button with href with shell scriptCao
S
0

You can try this code

<a href="" onkeypress="submit(this.form)"/>
<script>
    function submit(form) {
        form.submit();
    }
</script>
Spitsbergen answered 15/2, 2017 at 10:13 Comment(0)
C
0

I use more tricky way. make your button looks like <a href>

<button type="submit" style="background-color: transparent!important;border: none;padding: 0!important;color: #3c8dbc;cursor: pointer;box-sizing: border-box;">MY LINK BUTTON</button>

Capote answered 8/2, 2021 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.