Example is here.
I'm moving countries from one select box to another, when I submit the form I want the values in the right text box to be used by php. When I give the right box a name for a php array, like ToLB[] the Javascript fails. How can I handle this so that the submitted values will be used by php processes?
in forms it's a typical process to use an action and a method. This is declared within the form tag. For example
<form name='phpSend' method='post' action='myActions.php'>
Now when your form is submitted it is instantly 'posted' to the url myActions.php and is automatically declared as a $_POST array.
The names of the inputs become the array keys and the value becomes the value.
A basic method is to do a procedural action. Meaning if you leave the action attribute blank, the action will submit the form to the page you're already on and use if statements to check if the form has been submitted.
if(isset($_POST)&&isset($_POST['someName'])){
//form submitted!
}
Now, I've never used a multiple select before so you may want to var_dumb() or print_r() your output to double check but my guess is it'll be an Array within the $_POST array.
Submitting with javascript
if(document.getElementByName('phpSend').submit){//or however your checking
var selected=[];
for(var e=0;e<document.getElementByTagName('select').options.length;e++){
if(document.getElementByTagName('select').options[e].selected==true)selected[e]=document.getElementByTagName('select').options[e].value;
}
//then add the selected array to your preferred method of sending your data to your php document
}
I often encounter a situation like this and I usually submit the select options as a string.
Add an hidden field to your form:
<input type="hidden" name="valuesToSubmit">
<script type="text/javascript">
var selectobject=document.getElementById("myselect");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
</script>
In the PHP scripts that receive the posting data you can use the explode function to turn your sting into an array and then iterate on it ... depends what you need to do. Remember to remove the last unwanted ","
I have taken a look at your code.
There are some missing parts and amendments to do to make it works.
I didn't test the amendments but I think they should work.
1)you have to add the hidden field inside the form.
<form name="combo_box" action="test.php">
<input type="hidden" name="valuesToSubmit" value="">
2)Then you have to give the id to the select box because you use the id to reference the object like this var selectobject=document.getElementById("ToLB");
<select multiple size="10" name="ToLB" id="ToLB" style="width:150">
3)Change th submit button with a normal button so you can force the submit only when the loop is ended and the values have been passed into the hidden field.
<input type="button" name="submit" id="submit" value="Submit" onClick="updateValues()">
4)Force the submit at the end of the javascript
function updateValues(){
var selectobject=document.getElementById("ToLB");
var myValues = "";
for (var i=0; i<selectobject.length; i++){
myValues = myValues + selectobject.options[i].value + ",";
}
document.form.valuesToSubmit.value=myValues;
document.combo_box.submit();
}
Related
I have 3 different forms on a single page where the user can switch between using JS. The forms represent different information and only one can be submitted at a time where the user is then redirected to a different page based on the form they selected. The issue is that I have 2 input fields that are common to these forms so they are outside the forms. I am able to submit them alongside a form if I set the :
<input id="default" form="form1">
value.
So I figured it would be a simple thing to just add a function in each script where I hide/show the forms to also change that parameter to the form I want submitted however it doesn't seem to work.
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.form = "form2";
}
I have something like this but it doesn't change the form parameter.
You need to actually give your input an ID of default so you can target it:
<input form="form1" id="default">
use setAttribute
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.setAttribute("form", "form2");
console.log(input1.getAttribute("form"))
}
form2Search();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="default" form="form1">
I have a form which asks for employment history, where you have applied to college etc. So for example for colleges they applied to I have one text box at first and there is a button below that calls a javascript function to add another text input right below it. When I first made this form I was doing that with a few different pieces of data then once they were submitted I would get them from $_POST and put them in arrays then add each element of the array to the corresponding table in my db. All of a sudden though, I can no longer submit my form and I get a message telling me that I have tried to get an unspecified index. However when i inspect the text inputs in my browser they are correctly named. I read that I should name them college[] so that they all go into an array, but that also did not work.... now what?
js:
var numcol = 1;
function addnewschool(){
numcol++;
var container = document.getElementById("collegecontainer");
container.appendChild(document.createTextNode(numcol));
var input = document.createElement("input");
input.type = "text";
input.name = 'applied'+numcol;
container.appendChild(input);
container.appendChild(document.createElement("br"));}
html:
<p class="text-dark mb-4">List the Colleges you have applied to:<br>
<div id="collegecontainer" name="collegecontainer">
<input type="text" name='applied1'><br>
</div>
<input type="button" id="addcollege" name="addcollege" value="Add College"
onClick="addnewschool()"><br>
</p>
php:
$applied = array();
foreach($_POST['applied'] as $value){
array_push($applied, $value);
}
Update: Ok so I changed it to another way and that didn't work so i decided to just copy an earlier version of it which was working and paste it into the correct layout. And that worked... SO now that it was fixed i continued adding to it. I added "required" to a few tags, changed some styling a bit, and changed my javascript file a bit. But now I'm having the same issues as before. All of my POST arrays only have the first value in them. What could I have added that changed this? Has anyone ever had any issues like this?
Your first additional input should have index "applied1", not "applied2"
look at:
var numcol = 1; // put this to 0
function addnewschool(){
numcol++; // or move this to the end of the function
You don't need to add a different name for each input. Just use applied[] in all input names.
To get the array in PHP, just use $_POST['applied'].
If you want to use each of them later, you could use a foreach, like
foreach ($_POST['applied'] as $value) {
// Do what you want. Retrieve the value using $value
}
Or any other method you prefer.
Name your text input field(s) applied[] and when you process the form the post value of $_POST['applied'] will be an array already filled for you with however many entries were completed.
To get the data into your table:
foreach ($_POST['applied'] as $id => $applied) {
$sql = "INSERT INTO Colleges(id, college) VALUES('$id','$applied')";
if($conn2->query($sql) === TRUE){
echo "New Record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn2->error;
}
} // end of foreach
First post on Stack, thanks in advance.
I have a webpage that has 8 different forms, and on submit, I would like each one to display a different set of strings that I have stored in JavaScript arrays. The code to display the array works fine when used with only one form on the page, but I can't get it to work with all 8.
I have assigned each submit button an id, and am trying to assign that id to a variable called "chosen button" on submit. "chosen button" ultimately corresponds to the appropriate array, but only if the id is assigned to the variable. Here is html code:
<form id="ipsum-form" action="#" method="post">
<input type="submit" class="button" id="corporate" value="And So Forth.." />
And Javascript (my array variables and switch statement are obviously much longer):
var chosen_button = $("#ipsum-form submit").id;
var corporateIpsum = ["corporate jargon", "etc etc"];
switch (chosen_button){
case "corporate":
words = corporateIpsum;
break;
}
Is this the correct way to assign the submit button's ID to the variable? If not (or if this doesn't work for what I want), how can I make this work?
Cheers and I look forward to posting and learning more here in the future.
easy:
var chosen_button = $("#ipsum-form [type='submit']")[0].id;
or plain js:
document.forms[0].querySelectorAll('input[type="submit"]')[0].id;
Try var chosen_button = $('#ipsum-form .button').attr('id');. You can also use handlers to get the object (more useful in some situations) ex:
$('#ipsum-form input[type="submit"]').click(function () {
var chosen_button = $(this).attr('id');
// more code.
});
EDIT: Little bit more correct.
So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.
i have a little problem...i read a lot posts and i find some answers but...!i have multiple forms who created dynamically in PHP code!I have checkbox to every form and i check the forms to save the edits!my problem is when i check 3 forms only the first saved because only this post to save.php page!i make some changes to my code:
What i can do to make this code to send all forms to save.php page when i press th button save all
function save_all()
{
var all_elem=document.getElementsByTagName("*");
var same_id=new Array();
var index=0;
var answer=confirm("The prices from checked products will change!Are you sure");
if(answer)
{
for(var i=0;all_elem.length;i++)
{
if(all_elem[i].id=="form1"){
same_id[index++]=all_elem[i];
document.forms[all_elem[i]].action="save_all.php";//error
document.forms[all_elem[i]].submit();//error
}
}
}
//this is my form and i have while loop to create multiple forms
<form id="form1" name="form[<?=$form_counter++;?>]" method="post" class="checkboxes">
First, IDs must be unique. Period.
http://www.w3.org/TR/html4/struct/global.html#adef-id
Secondly, that's way too much code and very inefficient DOM traversal.
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++)
{
forms[i].submit();
}
But I doubt this will work. A form submittal reloads the page in some fashion. How can multiple form submissions occur at once (other than in the extremely obscure case of submitting multiple forms to different windows)?
And if they all must occur at once, why aren't they in a single form?
First. Use unique IDs always
Second. You can send the forms one by one, using Ajax, with jQuery or other library you like. But better, use a single form, adding all your input fields to it. So, when you submit your form, all data will be sent to your PHP script (hint: use unique names for each of the fields, so you can identify which product they represent)