Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  189] [ 2]  / answers: 1 / hits: 28751  / 13 Years ago, tue, february 7, 2012, 12:00:00

I'm new to javascript and am trying to start somewhat simple. Is it possible to create a function that contains a form object that can be populated by an onclick event?



Right now I have a page with 7 buttons, each button is a submit for a separate form, they all link to the same php file on the backside of my site where they are processed. I would like to somehow create one single form, possibly in a javascript function, that would accept variables from the buttons when clicked and then submit the form to my php script. it will technically function the same as it does now with 7 different forms, one for each button, but will hopefully cut back on the code.



This example is only how I logically thought it might work from a couple of weeks searching around the internet and gathering bits from here and there, but in reality it is far from functional.



example:



<script type=text/javascript>

function form_variables(opt1,opt2,opt3){

<form name='mySelectionForm' action='form.php?action=form_action' method='post' enctype='multipart/form-data'>
<input type='hidden' name='number' value=' + opt1 + ' />
<input type='hidden' name='id' value=' + opt2 + ' />
<input type='hidden' name='option' value=' + opt3 + ' id='options' />

</form>;

formObject.submit();
}


Then this would be populated by an onclick event like this.



<a href=javascript: void(0); onclick=form_variables('9','1','6'); title=submit_button1 value=Button 1 class=cssButton>My Selection</a>

More From » forms

 Answers
9

You're sort of on the right track. Rather than dynamically generating the form each time, your JavaScript could fill in the values of the hidden inputs and change the action of your form. So given this in your HTML:



<form name=mySelectionForm id=mySelectionForm action=form.php?action=form_action method=post enctype=multipart/form-data>
<input type=hidden name=number value= id=number />
<input type=hidden name=id value= id=id />
<input type=hidden name=option value= id=options />
</form>


Your JavaScript could look like this:



function postForm(number, id, option, action) {
var form = document.getElementById('mySelectionForm');
form.setAttribute('action', 'form.php?action=' + action);
document.getElementById('number').value = number;
document.getElementById('id').value = id;
document.getElementById('option').value = option;
form.submit();
}

[#87615] Saturday, February 4, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayla

Total Points: 14
Total Questions: 96
Total Answers: 123

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;