php mysql populate several dynamic dropdown list with add button - javascript

well this is my first post :)
I have a mysql DB and a form where you chose what you want to order. I have to say, that for input fields it works, but I have a problem when it comes to dynamic dropdowns. This is what I have (the two queries):
<?php
// Getting the data from mySQL table for first list box
$quer1="SELECT DISTINCT kategorija FROM artikli order by kategorija";
// for second dropdown list we will check if category is selected else we will display all the subcategories
if(isset($kategorija) and strlen($kategorija) > 0) {
$quer2="SELECT artikel FROM artikli where kategorija='$kategorija' order by artikel";
}
else {
$quer2="SELECT artikel FROM artikli order by artikel";
}
?>
<form id="forma_narocilo" action="naroci.php" method="POST">
<div class="input_fields_wrap">
<div>
<select name="kategorija" id="kategorija" ><option value="">Izberi kategorijo</option>
<?php
foreach ($dbo->query($quer1) as $row2) {
if($row2['kategorija']==$kategorija) {
echo "<option id='izbirna_kategorija' selected value='$row2[kategorija]' onchange='self.location=self.location+'?kategorija='+this.options[this.selectedIndex].value'>$row2[kategorija]</option>"."<br />";
}
else {
echo "<option id='izbirna_kategorija' value='$row2[kategorija]'>$row2[kategorija]</option>";
}
}
echo "</select>";
echo "<select name='artikel[]'><option value=''>Izberi artikel</option>";
foreach ($dbo->query($quer2) as $row) {
echo "<option value='$row[artikel]'>$row[artikel]</option>";
}
echo "</select>";
?>
<input type="number" name="kolicina[]"/><button class="add_field_button">Add line</button>
</div>
</div>
<input type="submit" id="shrani" value="Save" >
</form>
and this works just fine and it is updating the fields according to my needs, but now I need an "add" button which will insert another line with all three fields (category, item, nrPcs). For normal html inputs I used this:
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+x+'<input type="text" name="artikel[]"/><input type="text" name="kolicina[]"/>X</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
this will add a and 2 inputs inside. for the reload I use this:
function reload(){
var form = document.getElementById("forma_narocilo");
var val = form.kategorija.options[form.kategorija.options.selectedIndex].value;
self.location='?kategorija=' + val ;
}
function init(){
document.getElementById("kategorija").onchange = reload;
}
window.onload = init;
Now, my question is, how can I insert dropdowns when clicking the add button? Of course it should work as the first one e.g. it has to be independent...
thanks, erik

Related

Hide a button once a php input field $row has a value?

I am trying to hide a create account button if a value is already existing in the database. I only want the button to show if the Customer Number - '.$row["custno"].' field is empty.
I have tried hide/show and toggle using JS but I can't get it to only show the button if the field value of Customer Number - '.$row["custno"].' is empty. My last attempt was PHP but now I don't see the customer number or the button.
PHP Code
echo '
<div class="as-objecttitle">Create Customer Number</div>';
if(isset($_POST['custno'])){
echo '
<p>Customer Number - '.$row["custno"].' </p>
<p><a class="as-mainbtn" href="eappt_accountcreate.php?apptno=<?php echo htmlspecialchars($apptno); ?>">Create Account</a></p>'; }
Javascript Code
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ' <div class="as-objecttitle">Create Customer Number</div>
<p><input type="checkbox" id="myCheck" onclick="myFunction()"
checked> Customer Number - '.$row["custno"].' </p>
<p><i>If a customer number is listed, an account has already been
created.</i></p>
<br>
<p id="text" style="display:none"><a class="as-mainbtn"
href="eappt_accountcreate.php?apptno=<?php echo
htmlspecialchars($apptno); ?>">Create Account</a></p>';
}
} else {
echo "";
}
mysqli_close($conn);
?>
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
Using the JS method the user has to check the box to show the button. I want the button to be hidden if the Customer Number - '.$row["custno"].' is displaying and showing if the Customer Number - '.$row["custno"].' is empty. Not the best solution.
Thank you in advance for any recommendations you have.
You don't need to use javascript here. You can try by using empty
if (empty($row['custno']) {
echo 'Create Account';
} else {
echo 'Customer Number - '. $row['custno'];
}
Can you try this condition,
if($row['custno']) != ''){
echo "'Customer Number - '.$row['custno']";
}
else
{
echo "< ahref="">Your button</a>
}
Let me know if it is working for you. Thank you

Create dynamic text boxes then write to text file

So there must be an easier way to create this. I have a form with the following HTML:
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then added some JS to create new text boxes if a user needs to add more names:
Taken from: http://www.sanwebcorner.com/2017/02/dynamically-generate-form-fields-using.html
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
function check() {
var temp = document.getElementsByClassName("formElem");
if (document.getElementById("ckbox").checked) {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = false;
}
} else {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = true;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then need to write those appended values to a .CSV file using PHP and here is where I am having the issue:
<?php
// Receive form Post data and Saving it in variables
header('Location: thanks.html');
$Name = "";
$Name = #$_POST ['Name'];
// Write the name of text file where data will be store
$filename = "file.csv";
// Merge all the variables with text in a single variable.
$f_data= '
Names for people: '.$Name.' ';
$file = fopen($filename, "r+");
fwrite($file,$f_data);
fclose($file);
?>
What happens is that the last appended text box gets written into the csv file.Is there a way to pass these created text boxes so they can write to a the file? Really similar question: Pass dynamic text input to PHP in order to write to text file
But I'm not sure if this can be done with text boxes.
The problem is that every input you add has the name “name”, so PHP can only access the last one (which overwrote the others). To get around this, you can add an index to the input name or make an array of them. This can be achieved like so:
<input type="text" name="name[]"...>
So now, on the PHP script you can iterate over that array to get all the inputs, or implode all the elements into a variable:
<?php
$names = implode(", ", $_POST["name"]); // all the names, comma-separated
?>
Now you can use $names inside $f_data to see all the inputted fields.
(Thanks Fred-ii for the heads up about the quotes)

Multiple values inserted into 1 attribute in database

How can I get values from the added input field into my database? When I run this code the table shows "array" instead of the values entered..
Javascript to add input field:
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon[]">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
the Input field form:
<fieldset>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<label for="no_telefon[]">No.Telefon:</label> <input type="text" id="no_telefon[]" name="no_telefon[]" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/>
<label for="lokasi[]">Lokasi:</label> <input type="text" id="lokasi[]" name="lokasi[]" class="required input_field" required/>
</div>
and the PHP file to insert data into the database:
<?php
require("dbase.php");
if ($_POST) {
$id_akaun = isset($_POST['id_akaun']) ? $_POST['id_akaun'] : '';
$daerah = isset($_POST['daerah']) ? $_POST['daerah'] : '';
$kategori_akaun = isset($_POST['kategori_akaun']) ? $_POST['kategori_akaun'] : '';
$bahagian = isset($_POST['bahagian']) ? $_POST['bahagian'] : '';
$jenis = isset($_POST['jenis']) ? $_POST['jenis'] : '';
$no_telefon = isset($_POST['no_telefon']) ? $_POST['no_telefon'] : '';
$lokasi = isset($_POST['lokasi']) ? $_POST['lokasi'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$no_telefon' , '$lokasi', '".mysql_insert_id()."' )");
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='lamanutama.php'</script>";
}
?>
You need to use a loop to process all the no_telefon and lokasi fields:
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$akaun_id = mysql_insert_id();
foreach ($no_telefon AS $i => $telefon) {
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$telefon' , '$lokasi[$i]', '$akaun_id' )");
}
This will create a separate row in detail_akaun for each pair of no_telefon and lokasi.
BTW, you're creating duplicate IDs with id="no_telefon[]" and id="lokasi[]". IDs are supposed to be unique. All your labels with for="no_telefon[] and for="lokasi[] will be attached to the fields in the first row, not the one after it. Instead of using IDs and for, try wrapping your labels around the inputs:
<label>No.Telefon: <input type="text" name="no_telefon[]" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/></label>
Array data can't be saved in SQL because it's a php data type, and cannot be easily converted to a string.
So you will need to do the conversion by yourself.
A quick example:
$no_telefon_string = "";
foreach($no_telefon as $telefon)
{
$no_telefon_string .= $telefon.",";
}
$no_telefon_string = rtrim($no_telefon_string, ",");
Now you can insert the $no_telefon_string variable into the database.
To turn $no_telefon_string back into an array you can use:
$no_telefon = explode($no_telefon_string, ",");
$no_telefon will now be the array you originally got from the form post.

Dynamic Select Drop Box Generation Containing PHP Data

I need some help generating multiple select boxes. I am able to generate new boxes but they do not contain the SQL data that the boxes should have. I will link my javascript code first.
<script>
function add_file_field2(){
var container2=document.getElementById('file_container2');
var file_field2=document.createElement('select');
file_field2.name='animalCommony[]';
file_field2.type='animalCommony';
file_field2.value = 'animalCommony[]';
file_field2.text = 'animalCommony';
container2.appendChild(file_field2);
var br_field=document.createElement('br');
container2.appendChild(br_field);
}
function remove_field2() {
var container2=document.getElementById('file_container2');
lastChild = container2.lastChild;
if(lastChild !=0) {
container2.removeChild(lastChild);
file_field-= 1;
}
}
</script>
So I am not sure how I need to modify that code to generate the correct select boxes.
Here is my php code:
<?php
$db = get_db_connection('swcrc');
$db->connect();
$db->query("SELECT [ID], [Common_Name], [Scientific_Name] FROM dbo.All_Animals");
while($row = $db->fetch())
{
?>
<option value="<?php echo $row['Common_Name'];?> - <?php echo $row['Scientific_Name'];?>"><?php echo $row['Common_Name'];?> - <em><?php echo $row['Scientific_Name'];?></em></option>
<?php
}
?>
</select>
</div>
</p>
<p>
Add Another Animal
<br />
Remove Animal<br />
<br>
</p>
Finally I will have a screenshot of what it looks like after hitting the 'add another animal button' twice. Thank you for your help!
As you can see empty select boxes are generated.
Screen shot including an example of the kind of data that should populate the added boxes.
Screenshot of database
If all you want to do is copy the contents of the selection box, you don't need to query SQL again. Here's a javascript function that will do the copy, assuming your original selection box has id "myselect." I've also left you a jsfiddle below.
window.add_file_field2 = function () {
function copySelect(select) {
var newSelect = document.createElement('select');
newSelect.name = 'animalCommony[]';
newSelect.type = 'animalCommony';
newSelect.value = 'animalCommony[]';
newSelect.text = 'animalCommony';
for (var i = 0;i < select.options.length;i++) {
var option = document.createElement('option')
option.value = select.options[i].value
option.text = select.options[i].text
newSelect.appendChild(option)
}
return newSelect
}
var container2 = document.getElementById('file_container2');
container2.appendChild(copySelect(document.getElementById("myselect")));
var br_field = document.createElement('br');
container2.appendChild(br_field);
}
Here is a jsfiddle

PHP doesn't recognize fields dynamically added with JavaScript

I have a MySQL database of orders that each have various activities associated with them. My PHP/HTML page pulls down the activities when you click an order and allows the user to change attributes of the activities with a form. On submit another PHP file loops through activities in the table and runs an update query on the database. Works great!
I have recently added a JavaScript function that will add activities to the list (appendChild, createElement...). I then added to my PHP file an INSERT query for the new activities.
The problem is that when I run the update PHP file it is not looping through the newly added records that were added with JavaScript. I checked it by using <?php print $size = count($_POST['FcastID']) ?> and the value doesn't change when records have been added.
The records look fine when added to the table and the id and name convention match the other records. It seems like the page needs to be refreshed before the PHP file runs.
PHP file with dynamically created html form
<div id="submit"><form method="post" action="Up_Forecast.php"><input type="submit" value="Submit"></div>
....
<table id="fcast">
<?
$i=0;
while($row = mysqli_fetch_array($res_fcast))
{
echo "<tr id='fcastRow[$i]'>";
echo "<td class='medium'><input type='text' id='qtyJan[$i]' name='qtyJan[$i]' value='".$row[Jan]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyFeb[$i]' name='qtyFeb[$i]' value='".$row[Feb]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMar[$i]' name='qtyMar[$i]' value='".$row[Mar]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyApr[$i]' name='qtyApr[$i]' value='".$row[Apr]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMay[$i]' name='qtyMay[$i]' value='".$row[May]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJun[$i]' name='qtyJun[$i]' value='".$row[Jun]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJul[$i]' name='qtyJul[$i]' value='".$row[Jul]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyAug[$i]' name='qtyAug[$i]' value='".$row[Aug]."'/></td>";
echo "<td class='medium'><input type='text' id='qtySep[$i]' name='qtySep[$i]' value='".$row[Sep]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyOct[$i]' name='qtyOct[$i]' value='".$row[Oct]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyNov[$i]' name='qtyNov[$i]' value='".$row[Nov]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyDec[$i]' name='qtyDec[$i]' value='".$row[Dec]."'/></td>";
echo "<td class='medium'><input type='text' id='Totalqty[$i]' name='Totalqty[$i]' value='".$row[Total]."' disabled/></td>";
echo "</tr>";
++$i;
}
?>
<tr><td class="blank"></td><td class="mini"><input type="button" onclick="addRowYear(this)" value="Add"/></td></tr>
</table>
</form>
</div>
Javascript function to add row
function addRowYear(lastRow){
var rowNo = lastRow.parentNode.parentNode.rowIndex;
var newRow = document.getElementById("fcast").insertRow(rowNo);
newRow.setAttribute("id","fcastRow["+rowNo+"]");
var cell0 = newRow.insertCell(0);
cell0.setAttribute("class","mini");
var input0 = document.createElement("input");
input0.setAttribute("type","text");
input0.setAttribute("name","FcastID["+rowNo+"]");
input0.setAttribute("value","new");
cell0.appendChild(input0);
var cell1 = newRow.insertCell(1);
cell1.setAttribute("class","mini");
var input1 = document.createElement("input");
input1.setAttribute("type","text");
input1.setAttribute("name","Fcast_ActID["+rowNo+"]");
input1.setAttribute("id","Fcast_ActID["+rowNo+"]");
cell1.appendChild(input1);
var curAct = document.getElementById("selAct").innerHTML;
document.getElementById("Fcast_ActID["+rowNo+"]").value = curAct;
var cell2 = newRow.insertCell(2);
cell2.setAttribute("class","mini");
var input2 = document.createElement("input");
input2.setAttribute("type","text");
input2.setAttribute("name","Year["+rowNo+"]");
cell2.appendChild(input2);
var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
for (var i = 0; i < month.length; i++) {
//alert(month[i]);
x=3;
var cell = newRow.insertCell(x);
cell.setAttribute("class","medium");
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("class","numbers");
input.setAttribute("name","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("id","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("onkeyup","findTotal()");
cell.appendChild(input);
x=x+1;
}
var cell15 = newRow.insertCell(15);
cell15.setAttribute("class","medium");
var input15 = document.createElement("input");
input15.setAttribute("type","text");
input15.setAttribute("class","numbers");
input15.setAttribute("name","Totalqty["+rowNo+"]");
input15.setAttribute("id","Totalqty["+rowNo+"]");
cell15.appendChild(input15);
PHP Update - Called on Submit of form
$size = count($_POST['FcastID']);
$i = 0
while ($i < $size) {
$FcastID = $_POST['FcastID'][$i];
$ActID = $_POST['Fcast_ActID'][$i];
$Year = $_POST['Year'][$i];
$Jan = $_POST['qtyJan'][$i];
$Feb = $_POST['qtyFeb'][$i];
$Mar = $_POST['qtyMar'][$i];
$Apr = $_POST['qtyApr'][$i];
$May = $_POST['qtyMay'][$i];
$Jun = $_POST['qtyJun'][$i];
$Jul = $_POST['qtyJul'][$i];
$Aug = $_POST['qtyAug'][$i];
$Sep = $_POST['qtySep'][$i];
$Oct = $_POST['qtyOct'][$i];
$Nov = $_POST['qtyNov'][$i];
$Dec = $_POST['qtyDec'][$i];
$Total = $_POST['Totalqty'][$i];
$update = "UPDATE FCAST SET
Year='$Year',
Jan=replace('$Jan',',',''),
Feb=replace('$Feb',',',''),
Mar=replace('$Mar',',',''),
Apr=replace('$Apr',',',''),
May=replace('$May',',',''),
Jun=replace('$Jun',',',''),
Jul=replace('$Jul',',',''),
Aug=replace('$Aug',',',''),
Sep=replace('$Sep',',',''),
Oct=replace('$Oct',',',''),
Nov=replace('$Nov',',',''),
`Dec`=replace('$Dec',',',''),
Total=replace('$Total',',','')
WHERE
FcastID='$FcastID'";
mysqli_query($link, $update);
Without seeing your code, it is difficult to say. Something I have used in the past that works well is the following:
PHP:
foreach($_POST as $key => $value) {
//... $key is name of field, $value is the value
}
This goes through each individual field in the submitted form and reads the value in each. I've used this exact script for dynamically-created forms, and it works great. You have to be careful, though, if you use the same name for different fields, the values will be stored as arrays.
EDIT
HTML:
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
JavaScript:
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
It isn't all that important to know how the JavaScript code works. All you need to know is that clicking on the "Add" button will duplicate the field and clicking on "Remove" will remove the most recently added field. Try it out at the link provided.
PHP:
This is where the magic happens…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
Looks easy enough, right?
This PHP code is within the same file as the form, so first we check to see if the form has been submitted by checking for the name of the submit button if(isset($_POST['submit'])){…}.
If the form has been submitted, go through each submitted item foreach($_POST as $name => $item){…}.
The submit button counts as one of the fields submitted, but we aren't interested in storing that value, so check to make sure the value you are reading in is not from the submit button if($name != 'submit'){…}.
Finally, all the fields within this form have the same name field_name[]. The square brackets are used for multiple items that share the same name. They are then stored in an array. Read through each item within that array for the length of the array for($m=0; $m < sizeof($item); $m++){…} and then do what you'd like with each value. In this case, I've just printed them to the screen echo ($name.' '.$item[$m].'<br>');
Below are a couple screen-shots of the page…
Before submitting the form:
After submitting the form:
You can go to the page and view the code (right click -> View Source), but the PHP will not show up in the source. I assure you that all the PHP used for this is shown above - just the few lines.
If each item has a completely unique name (which you can achieve via JavaScript when adding fields), then you will not need to loop through the array of values (i.e. will not need for($m=0; $m < sizeof($item); $m++){…} block). Instead, you'll likely read the value using simply $item. If you name your fields with the square brackets (i.e. field_name[]), but only have one of that field, then reading a singular value may require $item or $item[0]. In that case you'll just have to test it and see. Some field types behave differently than others (i.e. input, text area, radio buttons, etc).
The Whole Thing
Here is the entire code for index.php - you can just copy and paste it and run it on your own server. Just make sure to change the name of the file in the action attribute <form> tag…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="../scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
<script>
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
</script>
</html>

Categories