I have a form that populates a select drop down using JavaScript + a PHP variable (that contains JSON information). The JavaScript creates the drop down perfectly however I can't work out how to retrieve the posted value on form submit.
I've tried retrieving the value using the simple post method to post the value, and retrieve it on the same page however nothing is passed through, does anyone know what I'm doing wrong here?
<?php
if (isset($_POST['save_settings_button']))
{
$site_name = $_POST["Site"];
}
?>
<form name='myform' method="POST" action=''>
<label for="Site">Site:</label>
<select id="Site"></select>
<div class=""><input class="cbp-mc-submit" type="submit" name="save_settings_button" value="Save Settings" /></div>
</form>
<script type="text/javascript">
var jsonData = {
"Table": <?php print $output;?>
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">- Select -</option>';
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].id + "'>" + jsonData.Table[i].name + "</option>";
}
$("#Site").html(listItems);
});
</script>
You didn't put any name for dropdown(SELECT) input add name="Site" then you can get input from it.
<form name='myform' method="POST" action=''>
<label for="Site">Site:</label>
<select id="Site" name="Site"></select>
<div class=""><input class="cbp-mc-submit" type="submit" name="save_settings_button" value="Save Settings" /></div>
</form>
Related
I am creating a webpage with ability to add input box dynamically , everything works fine. But whenever I add a new input box the value from all the input box added above that field get cleared automatically.
Here is the html which is generated on addition of the element
<div class="main_text_area" id="got_id_from_server">
<p>Add Delay For :</p>
<div class="remove_bg button btn" name="some_id_from_server"></div>
<p>
<div contenteditable class="text_im" placeholder="Enter Delay" id="some_id_from_server" onchange="post_delay(this)"></div>
</p>
<p>
<input class="text_im" placeholder="Select" type="text" id="some_id_from_server" list="some_id_from_server" onchange="post_delay(this)">
<datalist id="some_id_from_server">
<option value="Minutes"></option>
<option value="Hours"></option>
<option value="Days"></option>
</datalist>
</p>
</div>
This behavior occurs because adding new elements to your Dom will cause the Website to kind of render the view again & again so the (in this case) not stored values of a "input field given no ID attribute" you have inputted into your input-element will just reset.
So have a look at this two code snippets:
var count = 0;
function createInput(event) {
count++;
document.body.innerHTML += "<input value='Input #"+ count + "' / >"
event.preventDefault();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createInput()">Create Input</button>
Edit: Using jQuery will be the better solution so have a look at this code (To prevent the reset of the input fields you have to use "append()". Try it on your own!:
var count = 0;
$(function() {
$("#createInput").click(function(event) {
count++;
$('form').append('<input type="text" value="Input #' + count + '" />');
event.preventDefault();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="myForm" accept-charset="utf-8">
<button id="createInput">Create Input</button>
</form>
Okay it seems the original request was confusing so let me try re-wording. I have a form, see below code, with two Selects, users move things from the Available Locations list (One) to the Selected Locations list (Two) and input some other fields (I included one text field as an example), I need to be able to see what values are in the first select (One) and which are in the second list (Two)
There will be a large number of values so having the user just click or ctrl+click on the values they want isnt practical.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test for P1727410</title>
<script src="/ref-files/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#Two', '#One');
});
$('#right').on('click', function () {
moveItems('#One', '#Two');
});
$('#leftall').on('click', function () {
moveAllItems('#Two', '#One');
});
$('#rightall').on('click', function () {
moveAllItems('#One', '#Two');
});
});
</script>
</head>
<body>
<h2>Test for P1727410</h2>
Available Locations | Selected Locations
<form method="POST" action="#">
<select id="One" name="One" multiple="multiple">
<option value="1">Loc1</option>
<option value="2">Loc2</option>
<option value="3">Loc3</option>
</select>
<select id="Two" name="Two" multiple="multiple">
</select>
<br />
<input type="text" name="something" /><br />
<input type="hidden" name="form" value="1" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<input type="Submit" name="Submit" value="Submit" />
</form>
<p>
<?php
if(isset($_POST['form'])) {
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
?>
</p>
</body>
</html>
This question is confusing because we're not sure what you exactly want to show on the front-end (HTML + Javascript), what do you want to send to the back-end (PHP), and what do you want to insert/update/delete in the database.
The simplest solution I think of is the following:
You should have 3 tables in your database: users, locations, and user_locations. The user_locations should have at least 2 columns: "user_id" and "location_id".
HTML: Add a new html input hidden:
<input type="hidden" id="two_values" name="two_values" value="" />
Javascript: When user clicks submit button, take all values of the 2nd dropdown, and send them to the server. Like so:
<script>
$(document).ready(function() {
// on user clicks submit button, this code will be executed first
$('form').submit(function() {
// we'll take all values of the Two dropdown and put them in 1 string
var all_values = '';
$("#Two option").each(function() {
if(all_values === '') {
all_values += $(this).val();
} else {
all_values += ',' + $(this).val();
}
});
$('#two_values').val(all_values);
});
});
</script>
PHP: Get the two_values, and split them to array.
if(isset($_POST['form'])) {
$two_values_arr = explode(',', $_POST['two_values']);
// ...
}
PHP and MySQL: First, delete all previous user's locations:
$q = 'DELETE FROM `locations` WHERE `user_id` = ' . $user_id;
// run the $q ..
Then, do a loop to insert each value for this user
foreach($two_values_arr as $location_id) {
$q = 'INSERT INTO `user_locations` (user_id, location_id) VALUES (' . $user_id . ', ' . $location_id . ')';
// run the $q ..
}
Viewing HTML: When user views the page, you should fetch all user's locations, locations the user have should be printed to the Two dropdown, and ones he doesn't have in the One dropdown
Forgive me if this question is naive. I'm new to JavaScript and am learning my way through some setbacks with a form I'm using to display data.
An icao code is passed to the #depicao <select> menu via $_GET['icao'] in the JavaScript code at the bottom of the script. On page load, the <select> menu is populated with the $_GET['icao'] value.
After the #depicao <select> menu is populated, I'd like the form to automatically submit itself with its populated value. My train of thought is that if I include
document.getElementById("form").submit();
as the last line in the script, I can get the script to submit itself after it loads with the $_GET['icao'] value. Unfortunately, this hasn't been working, however.
NOTICE: The code contains multiple <input type="submit" name="submit"> buttons. I believe that this is the culprit.
See code below.
<form id="form" action="<?php echo actionurl('/schedules/view');?>" method="post">
<div id="tabcontainer">
<ul>
<li><span>Via departure airport</span></li>
<li><span>Via arrival airport</span></li>
</ul>
<div id="depapttab">
<select id="depicao" name="depicao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
<div id="arrapttab">
<select id="arricao" name="arricao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
</div>
<input type="hidden" name="action" value="findflight" />
</form>
<script type="text/javascript">
function formReset() {
document.getElementById("form").reset();
}
function setSelectedIndex(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++) {
if (s.options[i].value == valsearch) {
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
setSelectedIndex(document.getElementById("depicao"),"<?php if(isset($_GET['icao'])) { echo $_GET['icao']; } else { echo 'Select All'; } ?>");
document.getElementById("form").submit();
</script>
Form Auto Submission Confusion ?:
After the #depicao menu is populated, I'd like the form to automatically submit itself with its populated value.
How I understood you was that you want the form to be submitted automatically when the select menu is populated ? I think you meant when the user chooses a selection, it should submit automatically. If this is what you mean. Please add a onchange="//submitfunction()" onto the <select> tag
So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo
The problem:
I'm duplicating div's using a button.
Within the div's are parts of a form:
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
</div>
<input type="button" onclick="duplicate()" value="Add">
<button type="submit">Send</button>
</form>
I'm using this script:
<script type="text/javascript">
var i = 0;
var original = document.getElementById('duplicate');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicate" + ++i;
clone.style.clear = "both";
original.parentNode.appendChild(clone);
var tempId = document.getElementById("duplicate" + i);
tempId.childNodes[0].value=i;
}
</script>
As you can see, I'm trying to change the value of each input.
Adding it with 1 every time I duplicate the div.
Obviously it is not working. How do I do this?
Update:
So I've got this first part working.
Now I need to go deeper.
<form method="post" action="order-opstellen.php">
<div id="duplicate">
<input type="hidden" id="counter" value="0">
<div class="form-group dispWidth fl">
<label>Productnaam</label>
<select class="form-control dispWidth" name="productnaam"> <?php
$sql_products = "SELECT * FROM product ORDER BY naam";
$results = $conn->query($sql_products)->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $row) {
?>
<option value="<?= $row->productnr ?>"><?= $row->naam ?></option>
<?php }
?>
</select>
</div>
<div class="form-group dispWidth fl ml">
<label>Aantal</label>
<input type="text" name=amountCount class="form-control dispWidth" placeholder="Hoeveelheid">
</div>
</form>
What I want is every time I duplicate the div, the select-name has to be unique. Also the name of the last input has to be unique (amountCount).
Probably by con-catting the i variable behind them both (productnaam1, productnaam2, amountCount1.). How?!
childNodes[0] is the text node that contains the newline and indentation.
Try children[0] instead.
Also, tempId refers to the exact same thing as clone, so just use clone.children[0].value = i;