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.
My Selection
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();
}
Just make each link like this:
My Selection
Replacing {ID} with a number.
Then in your PHP file, use:
<?php
switch($_GET['id']) {
case 1:
$var['number'] = 9;
$var['id'] = 1;
$var['option'] = 6;
break;
...
}
?>
And so on for each case. This is a much better system, as it keeps your HTML tidy and removes the need for JavaScript.
Not to sure if i fully understand what you are trying to do. I think instead of making the form and submitting it every time you click one of your buttons can you just use this:
<script type="text/javascript">
function form_variables(opt1,opt2,opt3){
window.location('form.php?action=form_action&number='+opt1+'&id='+opt2+'&option='+opt3);
}
</script>
If I understand you correctly, you have 7 forms with 7 buttons and want to use scripting so that when one of the forms is submitted, you'll copy the values to another form then submit that. I don't see how that will "cut down on the code".
Seems to me like it is increasing the amount of code - forms don't need any scripting at all. You could just use one form with 7 submit buttons, then sort things out on the sever based on the button that was clicked.
Edit
If you use a single form with multiple submit buttons like:
<form action="form.php?action=form_action">
<input name="foo" value="bar">
<input type="submit" value="Submit 1" name="Submit 1">
<input type="submit" value="Submit 2" name="Submit 2">
</form>
then when the first submit is clicked the server will get:
...?foo=bar&Submit+1=Submit+1
and when the second button is clicked it will get:
...?foo=bar&Submit+2=Submit+2
so: one form, multiple submit buttons, no script, the server knows which one was clicked.
Of course you may want to use scripting to enhance the UI, but it isn't needed for the underlying functionality.
Related
Not sure how I did this last time or else I wouldnt asking here but here is what I'm trying to do.
I have the usual basic form with a javascript function that will submit the form. Question is that after the form is submitted, I have an if statement in PHP that echos a that the form has been submitted. Any help would be greatly appreciated.
//PHP
if($_POST['submitDelete']){
echo "welcome, You form has been submitted";
}
//HTML
<form id="form_id" action="" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" TYPE="submit">
</form>
<button type="button" onclick="myFunction()">Submit</button>
//JAVASCRIPT
<script>
function myFunction() {
document.getElementById("form_id").submit();
}
</script>
I can't seem to trigger the if statement in PHP. I also tried using the form name in the if statement and that didnt work either.
A form element must be told where to submit its data to when the submit event takes place. This is accomplished by setting the action attribute value for the form. Leaving that attribute empty does not implicitly set the form to post back to the current page. So, if you want to have a single page form/form processor, you need the action to be set to the current page file name:
<form action="currentPageFileName.php" method="post">
Next, there's no reason a single page can't have multiple forms on it. In that case you would need multiple submit buttons, each tied to a specific form. For this reason, you can't just drop a submit button anywhere on the page that you like unless you add the form attribute to the button to tie it back to the form it is supposed to trigger the submit for. Also, if you simply place the submit button within the form element it "belongs" to, you don't have to worry about this.
Also, you have some invalid HTML with:
<input type="hidden" name="submitDelete" TYPE="submit">
An element may not have the same attribute repeated within it (the case that you type the attribute in makes no difference since HTML is not case-sensitive). So, that code would wind up simply creating a submit button.
Lastly, if all you want to do with your submit button is cause its related form to be submitted, there is no need for JavaScript at all. That is what submit buttons do by default.
So, in the end, you can get rid of the JavaScript in your code completely and change your HTML to this:
<form id="form_id" action="currentFileName.php" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" value="true">
</form>
<button type="submit" form="form_id">Submit</button>
i am building a form and when i submit it it opens the action url. I want to submit the form on click button which should not open the target url but submit the request. as well as i want to print a message after submit and form should be cleared after submit.
<form id="contact" action="https://control.msg91.com/api/sendhttp.php" method="post">
<h3>Send SMS</h3>
<h4>Build in Process</h4>
<fieldset>
<input name="authkey" type="hidden" value="auth key as required"/>
<input name="mobiles" placeholder="Mobile Number" type="text" tabindex="1" maxlength="10" required >
</fieldset>
<fieldset>
<textarea name="message" placeholder="Type your message here...." tabindex="2" maxlength="320" required></textarea>
</fieldset>
<input name="sender" type="hidden" value="FAKEin" />
<input name="route" type="hidden" value="4" />
<input name="country" type="hidden" value="0" />
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</form>
any help how can i do this?
also can i add a hidden text in message tab that should add to the message tab in post/get as + instead of &
eg. actionurl.php?authkey=custommade&mobiles=9999999999&message=orginal+message+hidden+message&sender=FAKEin&route=4&country=0&submit=
You can also check the source code of page https://www.tricksbygoogle.com/sms/sms.php
Basically You can't .
The only solution here I see , is using ajax query and use javascript to clear form.
This example I provide is no redirections at all. What means you page will not be reloaded.
Maybe little jquery will help.
var result_func = function(response){
if(response.allOk){
$this.reset();
}
}
$('#contact').submit(function(e){
e.preventDefault()l
var $this = $(this);
var data = $this.serialize();
$.post($this.attr('action'),data,result_func.bind($this));
});
Header location will work , but user still will be redirected.
Based on your question, and the comments it looks like you're going to have to do a little bit of research. Here are some tips though.
If you would like to include the functions from a page without actually visiting the page, than you can use what is called an include statement. This will keep the browser from visiting that page while still executing it. - http://php.net/manual/en/function.include.php
To display a message you're going to need to hide and show the element with javascript. I would suggest viewing this question - Hide div after a few seconds
Basically on submit, you're going to want to check for the variables from your form. You would run a php if statement.
Then, if those variables exist you are going to want to include your action page.
In the same if statement, you're going to want to echo a <div> with a class that has some javascript attached to it to hide it after a few seconds.
The form will automatically clear on submit.
if($variable != null){
include '/action.php' // --- you can add some GET variables to the end of this if you would like to.
echo '<div id="message">Message sent</div>'
}
I am having a bit of trouble with some code. I am attempting to submit multiple forms. The first form is immediately visible, and the second can be added to the page when the user clicks an "Add Another Form" button (think of this like a referral system a user can add multiple referrals to).
So far I am able to submit one form and make more than one form appear on the page, however submitting any more than the first visible form is a challenge. Here is my code so far:
The form (all forms are clones):
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input id="name" type="text">
<input id="phone_number" type="text">
<input id="addanother" type="button" class="formBtn lrgBtn addanother" value="Add Another Form" >
<input type="hidden" name="retURL" value="https://www.example.com/thank-you/">
<input type="button" value="Submit Now" class="loopStarter multiRefHide formBtn" onclick="submitFormLoop()">
</form>
JavaScript for Form Submissions (SubmitFormLoop function):
var formCounter = 0;
var ellipsesCount = 0;
function submitFormLoop(){
if(typeof document.forms[formCounter]!= 'undefined'){
if($('.error:visible').length>0){
return false;
}
document.forms[formCounter].mySubmit.click()
if($('.error:visible').length>0) return false;
$('#submitting').show();
$('#supportCase').hide();
document.getElementById('submittingText').innerHTML = "Submitting your form(s)."
setInterval(function(){
ellipsesCount++;
var dots = new Array(ellipsesCount % 8).join('.');
document.getElementById('submittingText').innerHTML = "Submitting your form(s)" + dots;
}, 300);
setTimeout(function(){submitFormLoop()},1500)
formCounter++
}else{
window.location = "https://example.com/thank-you";
$('input[type="submit"],.addanother').hide()
formCounter = 0;
}
}
Again I can get the first one to submit, but I can't seem to get the function to loop. Any advice on this matter is very welcome, whether it is a small tweak or a recommendation to scrap my code completely.
Thank you all very much.
You cannot submit multiple form elements from the same page.
But you can get the behavior you desire two ways:
Submit the forms using AJAX (using XMLHttpRequest or a helper library like jQuery).
Reformat your inputs to use a single form element.
To do the latter, PHP programmers1 typically use the syntax:
<form action="www.example.com/submission.php" name="contactform" method="POST" class="biggerForm">
<input name="contacts[0][name]" type="text">
<input name="contacts[0][phone_number]" type="text">
<input name="contacts[1][name]" type="text">
<input name="contacts[1][phone_number]" type="text">
<input name="contacts[2][name]" type="text">
<input name="contacts[2][phone_number]" type="text">
</form>
Notice the [<integer>] in the syntax. In PHP, the $_POST variable will contain data like these as an indexed array.
Your button can then add additional input elements in the same format:
<input name="contacts[3][name]" type="text">
<input name="contacts[3][phone_number]" type="text">
On form submission, you can then retrieve these fields like so:
foreach($_POST['contacts'] as $person){
echo $person['name'];
echo $person['phone_number'];
}
1 I assume you're using PHP since your form's endpoint is submission.php.
1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!
Is possible to submit a from (synchronous normal classic way, no AJAX) with an additional POST var?
Using AJAX is easy:
$("#cpa").submit(function(e) {
e.preventDefault();
newvalues = { name: "John", time: "2pm" };
$.post(theurl, newvalues);
});
But i like to know if can SUBMIT (so the page reloads or goes to theurl) the form with additional data.
EDIT: Since there is a confusion on the comments, ill like to share more code:
http://jsfiddle.net/4zc4d/
Each time you click save the content of the alert is what i want to add to the form vars.
Use
<input type="hidden" name="country" value="Norway">
as seen in w3schools to submit fields that the user shall not see.
Beware: If the user cares to check sourcecode or traffic, he can find out the values.
EDIT:
About the additional fields in the jsfiddle: Did you realise you can send arrays directly?
<input type="hidden" name="id[]" value="1">
<input type="hidden" name="id[]" value="2">
<input type="hidden" name="id[]" value="3">
will result in
$_POST['id'] = array(1,2,3)
No need to concat values.
You can also add the hidden input via jQuery if you want to:
$("#cpa").submit(function(e) {
$(this).append('<input type="hidden" name="theName" value="some value" />');
});
As someone mentioned, add a hidden field to your form HTML
<input type="hidden" id="hidValue" />
Set the value required.
$("#hidValue").val("Anyvalue");