Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an external input value to form on submit

I have a typical form:

<form action="" accept-charset="utf-8" method="post">
    <textarea name="content"></textarea>
</form>

and an not-inside-a-form element:

<input type="password" name="password">

How do I add the value of password into the form when I submit the form?

$('form').submit(function(){
   //hmmm
});
like image 237
Jürgen Paul Avatar asked Aug 27 '12 04:08

Jürgen Paul


People also ask

How do you link a button to the outside of a form?

You can tie a submit button to a form that the button doesn't live inside of. The trick is to give the form an id and then reference that id with the button's form property. With this setup, clicking the Submit button will cause the form to be submitted.

Can I use javascript to submit a form?

The JavaScript form submission can be used for object creation and various attributes can also be used. The attributes can be class, id, tag, etc. Calling by attributes is quite simple, we just need to place the symbols properly.

Should the submit button be inside the form?

Yes, structurally the submit button needs to be inside a form element for the document to be valid X/HTML. But visually you can position the submit button anywhere you want with appropriate CSS (float, absolute/relative positioning, etc).


2 Answers

Create a hidden field in the form and copy the password field value to that field on submit. Like this.

<form action="" accept-charset="utf-8" method="post">
    <textarea name="content"></textarea>
    <input type="hidden" name="password" id="ps">
</form>

<input type="password" name="password" id="ps1">

And in on submit function.

$('form').submit(function(){
   $('input#ps').val($('input#ps1').val());
   return true;
});
like image 196
Vins Avatar answered Sep 18 '22 01:09

Vins


The not-yet-supported-but-HTML5-compliant way to do this "correctly" is to give your <input> element a [form] attribute:

<form id="foo">
    ...stuff...
</form>

<input type="password" id="bar" form="foo" />

Eventually you may be able to use this as a solution, but until more browsers support the [form] attribute, you'll have to polyfill it with JavaScript.

like image 43
zzzzBov Avatar answered Sep 21 '22 01:09

zzzzBov