i have a link that will call 3 js functions.
This is how i wrote the link :
echo "<td>
<a href='javascript:void(0)'
onclick=$('#f').window('open');
$(window).scrollTop($('#f').offset().top-60);
checkForMatch();
data-id='$row[0]'data-integ='$row[1]'data-type='$row[2]'
class='edit_conn'
>Edit</a></td>";
the onclick=$('#f').window('open');will open a modal and work just fine.
the $(window).scrollTop($('#e').offset().top-60); will reposition the modal and also work just fine.
however the checkForMatch(); only work on second click (this one will disable input based on textbox value)
Any clue why the checkForMatch(); function only work on second click ?
please pardon my potato english.
Edit :
here is how i wrote the checkForMatch function :
function checkForMatch() {
var input1 = document.getElementById("typeconn_edit");
var input2 = document.getElementById("countryphone_edit");
if (input1.value == 'mobile_Phone') {
input2.disabled = true;
} else {
input2.disabled = false;
}
}
Edit2 :
The "f" is a jqueryUI modal window this is how its written :
<div id="f" class="easyui-window formedit" title="Entry identity
Connectivity" data-options="modal:true,closed:true,iconCls:'icon-save'">
<?php include 'form_edit_conn.php'; ?>
</div>
the "idconn_edit", "integconn_edit", "typeconn_edit" are input textboxes
<input type="text" id="idconn_edit" name="id">
<input type="text" id="integconn_edit" name="integ_conn">
<input type="text" id="typeconn_edit" name="type_conn">
and this is how i pass values to those 3 textboxes :
(document).on("click", ".edit_conn", function () {
var id = $(this).data('id');
var type = $(this).data('type');
var integ = $(this).data('integ');
$(".formedit #idconn_edit").val( id );
$(".formedit #integconn_edit").val( integ );
$(".formedit #typeconn_edit").val( type );
});
and the "countryphone_edit" is a selectbox
<select id="countryphone_edit">
<option value="0">Please Select</option>
<?php
$query = mysql_query("SELECT Country_Name FROM tbl_country");
while ($row = mysql_fetch_array($query)) {
?>
<option value="<?php echo $row['Country_Name']; ?>">
<?php echo $row['Country_Name']; ?>
</option>
<?php
}
?>
</select>
and sorry there's no 'e' i didnt realize that one since 'f' already on a good position.
I solved it,
i added checkForMatch(); function on the passing values code (edit_conn)
(document).on("click", ".edit_conn", function () {
var id = $(this).data('id');
var type = $(this).data('type');
var integ = $(this).data('integ');
$(".formedit #idconn_edit").val( id );
$(".formedit #integconn_edit").val( integ );
$(".formedit #typeconn_edit").val( type );
checkForMatch();
});
i honestly dont understand why adding checkForMatch(); there solved my problem, but i think thats enough. Ty guys
Related
I'm using dropdown when selected first dropdown, based on first dropdown selected it will show second dropdown. Each dropdown have data from database and the problem is i want to insert it into new table on database based on dropdown selected.
All the code on the same page, this is the php.
<?php
$sql= mysql_query("SELECT KodeMapel,NamaTema FROM mapel");
while ($row = mysql_fetch_array($sql))
{
$tema[] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['NamaTema']);
}
$query = mysql_query("SELECT KodeMapel, Subtema FROM subtema");
while ($row = mysql_fetch_array($query))
{
$subtema[$row['KodeMapel']][] = array("KodeMapel" => $row['KodeMapel'], "val" => $row['Subtema']);
}
$jsonTema = json_encode($tema);
$jsonSubTema = json_encode($subtema);
?>
This is the form, included javascript on it. Inside the javascript there's php code.
<script type='text/javascript'>
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
function loadtema(){
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema;
for(var i = 0; i < tema.length; i++){
select.options[i] = new Option(tema[i].val,tema[i].KodeMapel);
}
}
function updateSubTema(){
var PilihTema = this;
var idtema = this.value;
var PilihSubtema = document.getElementById("PilihSubtema");
PilihSubtema.options.length = 0; //delete all options if any present
for(var i = 0; i < subtema[idtema].length; i++){
PilihSubtema.options[i] = new Option(subtema[idtema][i].val,subtema[idtema][i].KodeMapel);
}
}
</script>
<body onload='loadtema()'>
<select id='PilihTema' name='PilihTema' class='form-control11'>
</select>
<select id='PilihSubtema' name='PilihSubtema' class='form-control11'>
</select>
<button input class="btn btn-success" id="submit" type="submit" name="add" value="Simpan" onclick="return(submitmapel());"/>
<i class="fa fa-save fa-fw"></i> Simpan
So far I see some errors in your code.
select.onchange = updateSubTema;
You are missing () for the function. Should be select.onchange = updateSubTema();
I'm not sure if var PilihTema = this; will actually select anything, personally i'd do it the following way.
loadTema function:
var select = document.getElementById("PilihTema");
select.onchange = updateSubTema(select.value);
updateTema function
function updateTema(pilihTema){
//Your code here
}
EDIT: If you mean you want to add an item per run through your for loop, I would suggest doing it the following way (I use jQuery as it is much easier in my opinion):
$(document).ready(function(){
<?php
echo "var tema = $jsonTema;";
echo "var subtema = $jsonSubTema;";
?>
//Load Tema
$.each(tema, function (i, item) {
//I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihTema").append(new Option(item.val, item.KodeMapel));
});
//Called when the first select field is changed.
$("#PilihTema").change(function(){
//Get value of first select fields' selected item
var pilihValue = $("#PilihTema option:checked").val();
//Remove all the options from the second select field
$("#PilihSubtema").html("");
//For each subtema, with first select fields value, add option to second select field
$.each(subtema[pilihValue], function (i, item) {
//Again, I am unsure as to what you mean by KodeMapel, though if this is associative arrays encoded as JSON, you will want to use item[val] and item[KodeMapel]
$("#PilihSubtema").append(new Option(item.val, item.KodeMapel));
});
});
});
I'm using codeigniter 3.0.4 and now stuck on a basic problem. I have an <input type='text'> with a default value generated using Jquery.
My Question, how do I check whether the value has been changed or not when I submit a form?
If the value now is different from default given value, it'll do a callback validation (it's actually to check email availability). Otherwise if the value is still the same as the default given value it will skip the callback validation.
This is my modal
<div class="modal-body" id="myModalBody">
<form id="contactform" role="form" method="POST" action='<?php echo base_url('administrator/kategori/editcategory');?>' >
<div class="form-group">
<label for="kategori"> Nama Kategori </label>
<input type="hidden" name="id" class='id' id='id'>
<input type="text" class="form-control edit-category" name='edit-category' id="edit-category" required autofocus>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success confirm-edit"> Edit Data </button>
</form>
</div>
as you can see, that form above submits the data to administrator/kategori/editkategori
and this is my editkategori() function
public function editcategory(){
if($this->input->post()){
$this->form_validation->set_rules('kategori', 'Kategori Baru', 'required|callback_correctcategory');
if($this->form_validation->run() == FALSE){
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"id" => $this->input->post('id'),
"kb" => $this->input->post('kategori')
);
$result = $this->admincrud->editcategory($tobesent);
if($result){
$this->session->set_flashdata('result', 'Kategori Sukses Diubah');
redirect('administrator/kategori');
}
}
} else {
redirect('administrator/kategori');
}
}
This is the JQuery function to automatically give values to corresponding text when the modal above is shown
$('.toggle-edit-modal').click(function(){
var id = $(this).closest('tr').find('td:eq(0)').text();
var categoryname = $(this).closest('tr').find('td:eq(1)').text();
$('.id').val(id);
$('.edit-categoryname').val(categoryname);
})
in the set of validation rules, I put the callback correctcategory(), and this is the correctcategory() function :
public function correctcategory($str){
$sterilizedkey = strtoupper(trim(str_replace(" ", "", $str)));
$tobeshown = ucfirst(strtolower($sterilizedkey));
$this->CI->db->select("upper(trim(REPLACE(`CategoryName`, ' ',''))) as `CategoryName`");
$this->CI->db->from('category');
$result = $this->CI->db->get()->result_array();
$data = array();
foreach ($result as $key => $value) {
$data[] = $value['CategoryName'];
}
if(in_array($sterilizedkey, $data)){
$this->set_message('correctcategory', 'The faculty has been registered before');
return false;
} else {
return true;
}
}
With the code above, the system will evaluate every value submitted through the form.
The problem comes when I open the modal, and a textbox with default given value appears. How can I skip the correctcategory validation if I directly submit the form but without changing the value of the textbox, or when the new value and the old given one are exactly the same ?
you have to store the original value in a hidden text box. and check it with the text box which has values.
for eg:
<input type="text" id="orig" value="your email">
<input type="hidden" id="hid" value="your email">
then in jquery on submit check like the following
var original = $('#orig').val();
var static = $('#hid').val();
if(original == static){
alert("not changed");
}else{
alert("changed");
}
Note: this code is only for example as you did'nt shared any of your code
If the value being set by Jquery is known by you, then the controller should as well be aware( guess this is the category database value)
Based on the assumption that default value is known.
To solve this, the controller function needs to be aware of the default value you are setting for the input.
class Categories extends CI_Controller {
public function edit()
{
// form submited?
If ( $this->input->post())
{
$this->load->model('category_model');
$error = null;
$success = false ;
$id = $this->input->post('id');
// now you were looking for 'kategori' instead of 'edit-category'
$posted_cat_name = $this->input->post('edit-category');
// get the db record
$category = $this->category_model->fetch( array('id' => $id ));
if( !$category->id)
{
$error = 'Category not exist' ;
// set flash and redirect
redirect('categories/admin_list');
}
// category remain the same
If( $posted_cat_name == $category->name)
{
$error = "No changes made" ;
}
else if( $this->category_model->update($id , $posted_cat_name) == false)
{
$error = 'Error occured updating category' ;
// get the error and log_message() for debuging
}
else
{
$success = true ;
// set flash data and redirect
}
}
// do you need this remaining code? aren't you suppose to redirect back to admin list where the form was posted ?
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
}
}
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.
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
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>