I have form in view (i'm using codeigniter), in the form there's an element (array) like this code below:
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0">
<col class="con1">
<col class="con0">
<col class="con1">
<col class="con0">
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="1">1</div>
<input type="hidden" name="kd_obat_1" id="kd_obat_1" class="kd_obat" value="02">
</td>
<td>
<input type="text" name="nama_obat_1" id="nama_obat_1" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_1" id="dosis_1" class="dosis input-small valid">
</td>
<td>
<select name="satuan_1" id="satuan_1" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_1" id="jumlah_1" class="jumlah input-large valid">
</td>
</tr>
<tr>
<td>
<div id="2">2</div>
<input type="hidden" name="kd_obat_2" id="kd_obat_2" class="kd_obat" value="01">
</td>
<td>
<input type="text" name="nama_obat_2" id="nama_obat_2" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_2" id="dosis_2" class="dosis input-small valid">
</td>
<td>
<select name="satuan_2" id="satuan_2" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_2" id="jumlah_2" class="jumlah input-large valid">
</td>
</tr>
</tbody>
</table>
How can i count an array and get post values in controller codeigniter? i try this code doesnt work :
foreach ($_POST as $key=>$val) {
$$key = $val;
}
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== "")
{
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
Thanks in advance!
EDIT :
i need to count field with name 'kd_obat_x' where x = 1 to n, based on user input. i need algorithm to get how many variables posted based on user input and so on get the data. here's my complete code:
view.php
<h4>Step 3: Obat</h4>
<p>
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0" />
<col class="con1" />
<col class="con0" />
<col class="con1" />
<col class="con0" />
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</thead>
<tbody></tbody>
</table>
</p>
<p>
<i class="icon-plus icon-white"></i> Tambah
<i class="icon-trash icon-white"></i> Hapus
</p>
my.js
<script type="text/javascript">
// Autocomplete Obat
jQuery(function() {
var counter3 = 1;
var options = {
source: '<?php echo base_url(); ?>admin/autoCompleteObat',
minLength: 2,
focus: function( event, ui ) {
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
select: function( event, ui ) {
//event.preventDefault();
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
messages: {
noResults: ''
}
};
jQuery('input.nama_obat').live("keydown.autocomplete", function() {
jQuery(this).autocomplete(options);
});
var addInput = function() {
if (counter3 > 1){
jQuery('a#removeObat').removeAttr('disabled');
}
var inputHTML = '<tr><td><div id="'+counter3+'">'+counter3+'</div><input type="hidden" name="kd_obat_'+counter3+'" id="kd_obat_'+counter3+'" class="kd_obat" /></td><td><input type="text" name="nama_obat_'+counter3+'" id="nama_obat_'+counter3+'" class="nama_obat input-large" /></td><td><input type="text" name="dosis_'+counter3+'" id="dosis_'+counter3+'" class="dosis input-small" /></td><td><select name="satuan_'+counter3+'" id="satuan_'+counter3+'" class="satuan uniformselect" style="width:100px;"><option name="-">Pilih Satuan</option><?php foreach($list_satuan_kecil as $lsk) : ?><option value="<?php echo $lsk['kd_sat_kecil_obat']; ?>"><?php echo $lsk['sat_kecil_obat']; ?></option><?php endforeach; ?></select></td><td><input type="text" name="jumlah_'+counter3+'" id="jumlah_'+counter3+'" class="jumlah input-large" /></td></tr>';
jQuery(inputHTML).appendTo("table#tbl-obat tbody");
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
counter3++;
};
var removeInput = function() {
counter3--;
if(counter3 == 1){
jQuery('a#removeObat').attr('disabled','disabled');
//alert("Minimal sisa 1!");
counter3++;
//console.log('Jika Counter == 1 :' + counter3);
}else{
jQuery("table#tbl-obat tbody tr:last").remove();
//console.log('Jika Counter != 1 :' + counter3);
}
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
};
if (!jQuery("table#tbl-obat tbody").find("input.nama_obat").length) {
addInput();
}
jQuery("a#addObat").click(addInput);
jQuery("a#removeObat").click(removeInput);
});
</script>
admin.php (controller)
function autoCompleteObat()
{
if (isset($_REQUEST['term'])){
$q = strtolower($_GET['term']);
$output = $this->m_crud->get_obat($q);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
}
}
/***MASTER PELAYANAN***/
function pelayanan($par1 = '', $par2 = '', $par3 = '')
{
if (!$this->session->userdata('logged_in') == true)
{
redirect('login');
}
if ($par1 == 'tambah') {
$trans_id = $this->m_crud->generate_transaksi();
$pelayanan['kd_trans_pelayanan'] = $trans_id;
$pelayanan['kd_rekam_medis'] = $this->input->post('kd_rekam_medis');
$pelayanan['tgl_pelayanan'] = $this->functions->convert_date_sql($this->input->post('tgl_pelayanan'));
$pelayanan['kd_jenis_layanan'] = $this->input->post('kd_jenis_layanan');
$pelayanan['kd_unit_pelayanan'] = $this->input->post('kd_unit_pelayanan');
$pelayanan['kd_puskesmas'] = 'P3271010101'; //$this->session->userdata('kd_puskesmas'); // harusnya diambil dari session
$pelayanan['kd_dokter'] = $this->input->post('kd_dokter');
$pelayanan['kd_petugas'] = $this->input->post('kd_petugas');
$pelayanan['kd_status_pasien'] = $this->input->post('kd_status_pasien'); // blm
$pelayanan['anamnesa'] = $this->input->post('anamnesa');
$pelayanan['cat_fisik'] = $this->input->post('cat_fisik');
$pelayanan['cat_dokter'] = $this->input->post('cat_dokter');
$pelayanan['kd_bed'] = $this->input->post('kd_bed');
$pelayanan['no_rujukan'] = $this->input->post('no_rujukan');
$pelayanan['tempat_rujukan'] = $this->input->post('tempat_rujukan');
// Pelayanan Obat
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== ""){
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
/* insert db here */
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
}
}
and finally my model m_crud.php
function get_obat($q){
$this->db->select('kd_obat,nama_obat');
$this->db->like('nama_obat', $q);
$this->db->or_like('kd_obat', $q);
$query = $this->db->get('obat');
$results = array();
if($query->num_rows > 0){
$i = 1;
foreach ($query->result_array() as $row){
$results[$i]['label'] = $row['kd_obat'].' - '.$row['nama_obat']; //build an array
$results[$i]['value'] = htmlentities(stripslashes($row['nama_obat']));
$results[$i]['kd_obat'] = htmlentities(stripslashes($row['kd_obat']));
$i++;
}
}
return $results;
}
You can count all element with 'kd_obat_' using this code:
$count=0;
foreach($arr as $key=>$value){
$pos = strpos($key,'kd_obat_');
if($pos!==false){
$count++;
}else{
continue;
}
}
echo $count;
You can use following snippet for post values:
$this->input->post();
Count Array tuples:
$elements = count($this->input->post());
You can use input library for getting 'POST' data in codeIgniter Framework,
Please add following code in your code and you will get array in post type.
$postData = $this->input->post(); print_r($postData);exit;
Hope this will work for you.
Assuming that you want the values of nama_obat_1, nama_obat_2, nama_obat_3, etc
First of all you need to indicate an array in your name fields as follows
nama_obat[] for the first field, nama_obat[] for the second field and so on
optionally you can do it like this
nama_obat[1] for the first field, nama_obat[2] for the second field and so on
Then in your Controller if you var_dump() this $this->input->post('nama_obat')
will outputs an array of your values.
Then for the counting part, you can use PHP count() function.
If your $this->input->post('nama_obat'); is a one level array then you can use
count($this->input->post('nama_obat')); // or store it in a variable then count it
and if your array is a multilevel array like
array(
'foo' => 'bar',
'myfoo' => array('mybar'=> 'myfoo')
)
Then you can use
count($this->input->post('nama_obat'), COUNT_RECURSIVE); // or store it in a variable then count it
Related
Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:
1) dashboard.php will display 3 select option which is team, time from and time to
2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).
3) All data row will be listed and each data have a delete button. User can delete data based on data row.
My problem is, the data is not deleted.
Below is my current code.
dashboard.php
<select class="form-control" name="team" id="team">
<option value="">Please select...</option>
<?php foreach ($data as $row2): ?>
<option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
<?php endforeach ?>
</select>
<td width="1%"></td>
</td>
<td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
<td width="1%"></td>
<td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
</tr>
</table><br>
<div id = "dashboard">
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from").datepicker().attr("autocomplete", "off");;
$("#to").datepicker().attr("autocomplete", "off");;
});
$('#range').click(function(){
var from = $('#from').val();
var to = $('#to').val();
var team = $('#team').val();
if(from != '' && to != '' && team != '')
{
$.ajax({
url:"range.php",
method:"POST",
data:{from:from, to:to, team:team},
success:function(data)
{
$('#dashboard').html(data);
}
});
}
else
{
alert("Please select both team and date range");
}
});
if($('#from').val() && $('#to').val() && $('#team').val()){
$('#range').click();
}
});
</script>
range.php (AJAX)
<?php
require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";
$email = $_SESSION['login_user'];
if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{
$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();
if($sql->rowCount() > 0)
{
echo'
<form method="post" action="">
<div class="row" style="height: 300px; overflow-y: scroll;">
<div class="col-lg-12 grid-margin stretch-card">
<table class = "table-bordered" width = "100%">
<thead>
<tr>
<th>id</th>
<th>Date</th>
<th>Status</th>
<th colspan = "2" width = "7%">Action</th>
</tr>
</thead>
<tbody>';
while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$datereport = $row['report_date'];
$datereport2 = strtotime($datereport);
$report_date = date('d M Y', $datereport2);
$report_id = $row["report_id"];
echo'<tr>';
echo '<td>'.$report_id.'</td>';
echo '<td>'.$report_date.'</td>';
echo '<td align="center">';
echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';
echo '<td align="center">';
echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
echo '<button type = "submit" class="btn-danger">Delete</button>';
echo '</form>';
echo '</td>';
echo '</tr>';
}
}
delete_ajax.php
<?php
require_once '../../../config/configPDO.php';
$report_id = $_POST['report_id'];
$sql = "DELETE FROM ot_report WHERE report_id=:report_id";
$query = $conn->prepare($sql);
$query->execute(array(':report_id' => $report_id));
header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");
?>
Can anyone knows what is the problem? The data cannot deleted!. Help anyone
maybe this is because in the range.php file you have 2 form tags
first is outside while function
<form method="post" action="">
and second one is in while function
<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
try removing the first one
I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}
This is the controller:
public function routeupdateAction() {
$iRoute = IV_Http_Base::getParameter( 'id', IV_Http_Base::HTTP_POST );
$sPath = IV_Http_Base::getParameter( 'path', IV_Http_Base::HTTP_POST );
$sModule = IV_Http_Base::getParameter( 'module', IV_Http_Base::HTTP_POST );
$sController = IV_Http_Base::getParameter( 'controller', IV_Http_Base::HTTP_POST );
$sAction = IV_Http_Base::getParameter( 'action', IV_Http_Base::HTTP_POST );
$iAccessRole = IV_Http_Base::getParameter( 'accessRole', IV_Http_Base::HTTP_POST );
$iRoleCompareOperator = IV_Http_Base::getParameter( 'roleCompareOperator', IV_Http_Base::HTTP_POST );
$oRoute = Default_Model_RouteEntity::getInstanceById( $iRoute );
if( is_object( $oRoute ) && $oRoute instanceof Default_Model_RouteEntity ) {
$oRoute->setPath( $sPath );
$oRoute->setModule( $sModule );
$oRoute->setController( $sController );
$oRoute->setAction( $sAction );
$oRoute->setAccessRole($iAccessRole);
$oRoute->setRoleCompareOperator($iRoleCompareOperator);
$oRoute->save();
$aReturn = array( 'valid' => 'true' );
} else {
$aReturn = array( 'valid' => 'false' );
}
echo json_encode( $aReturn );
}
}
The route.js file
var ROUTE = new function () {
var oGlobal = this;
this.sSaveUrl = '';
this.setSaveUrl = function (_sUrl) {
this.sSaveUrl = _sUrl;
}
this.setEventSubmit = function () {
$('[id^="route_update"]').each(function () {
$(this).click(function () {
var oData = $(this).closest('tr').find('input').serializeArray();
console.log(oData);
oReq = $.post(oGlobal.sSaveUrl, oData, function (data) {
if (data['valid'] != "true") {
//console.log('error');
//Fade in
$('#comment').html('Insert Success').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
} else {
// console.log('success');
//Fade in
$('#comment').html('Insert Success').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
}
return false;
}, 'json');
return false;
});
});
}
this.init = function () {
this.setEventSubmit();
}
}
and the html markup
<form class="form-inline" role="form">
<form class="well form-inline">
<table class="table table-bordered" width="100%">
<tr>
<th width="13%">Path</th>
<th width="13%">Module</th>
<th width="13%">Controller</th>
<th width="13%">Action</th>
<th width="13%">Access Role</th>
<th width="13%">Compare Operator</th>
<th width="9%">Submit</th>
</tr>
<?
$aRoutes = $this->getValue('aRoutes');
if( count($aRoutes) == 0 ) {
?>
<tr>
<td colspan="7">No routes found!</td>
</tr>
<?
} else {
/**
* #var Default_Model_RouteEntity $oRoute
*/
foreach ( $aRoutes as $oRoute) {
?>
<tr>
<td width="13%">
<input type="text" name="path" value="<?= $oRoute->getPath(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getModule(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getController(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getAction(); ?>"/>
</td>
<td width="13%">
<input type="text" class="form-actions" value="<?= $oRoute->getAccessRole(); ?>"/>
</td>
<td width="13%">
<input type="text" value="<?= $oRoute->getRoleCompareOperator(); ?>"/>
</td>
<td width="9%">
<input type="hidden" name="id" value="<?= $oRoute->getId(); ?>" />
<button type="button" class="btn btn-default btn-sm" id="route_update">Edit</button>
<div id="comment"></div>
</td>
</tr>
<?
}
} ?>
</table>
</form>
</form>
<? $this->addJs('admin/cms/route'); ?>
<script type="text/javascript">
$(document).ready(function () {
ROUTE.setSaveUrl('<?=IV_Url_Base::url( 'admin_cms_routeupdate' ); ?>');
ROUTE.init();
});
</script>
My request is, as you can see the basic features are ready...Now what I need to implement is to save the data when i change a row.
This should be needed in js without refreshing the page lots of times and if the data are saved correctly you have a fade displaying the right saving..
How do I save the data when a row is changed?
Delete the "form" tags.
Use jQuery to set onclick events on the buttons.
Use parent('tr') (parent) to retrieve row element.
Using the row element use each to iterate through td tags and save the data to some array: $('td', $row).each(function () { /* parse td element */ });
Send array to PHP script using AJAX.
Save the data in PHP script and display result to AJAX using status codes (200 - OK, 4** - ERROR)
If everything is working, use jQuery to do the animations you want.
I have a php script that ask the user to upload a csv, then it display the result before importing and ask the user to map the fields corresponding to the database tables. It work fine.
My problem is that it seems that the server restrict the number of post or insert that can be made. So I can insert like 75 lines. But I have something like 600 lines. How could I split those like maybe in different files or maybe INFILE function.
I'm a little bit loss on that one. Because also, the user can select wich record he wants to be inserted with checkboxes.
<?php
setlocale(LC_ALL,"en_US.UTF-8");
ob_start();
if(!isset($_SESSION))
{
session_start();
}
//variables
$upload_file='';
$err='';
$msg='';
include "config.php";
if(isset($_POST['frm_type'])) // Insert Records
{
if(isset($_POST['frm_type']) && $_POST['frm_type']=='custom')
{
if(count($_POST["chk"])>0)
{
$count_cols=$_POST["h_cols"];
foreach($_POST["chk"] as $index)
{
$query="";
$dyn_query="";
$select_where="";
$date_reg=date('Y-m-d');
//STATIC COLUMN
$query = "cat_id='".$_POST["cat_id".$index]."'";
$query .= ",date_reg='".$date_reg."'";
$query .= ",user_id='".$_SESSION['user_id']."'";
$query .= ",type_client='".$_SESSION['cltype']."'";
$query .= ",birthday_switch='1',";
//DYNAMIC COLUMN
for($s=0; $s<$count_cols;$s++)
{
if(isset($_POST["colum_".$s]) && $_POST["colum_".$s]!='')
{
$value=Add_Slashes($_POST["row_".$s."_".$index]);
$dyn_query[]="".$_POST["colum_".$s]."='".$value."'";
}
if($_POST["colum_".$s]=="full_name")
{
$value=trim($_POST["row_".$s."_".$index]);
if($value!="")
{
$allow=1;
}
else
{
$allow=0;
}
}
}
if($dyn_query)
{
if($allow==1)
{
$query .=implode(',',$dyn_query);
$select_where[]="cat_id='".$_POST["cat_id".$index]."'";
$select_where[]="user_id='".$_SESSION['user_id']."'";
$select_where[]="type_client='".$_SESSION['cltype']."'";
for($t=0; $t<$count_cols;$t++)
{
if(isset($_POST["colum_".$t]) && $_POST["colum_".$t]!='')
{
$value=Add_Slashes($_POST["row_".$t."_".$index]);
$select_where[]="".$_POST["colum_".$t]."='".$value."'";
}
}
$select_where_query=implode(' AND ', $select_where);
$re = mysql_query("Select cat_id From clients Where $select_where_query");
if(mysql_num_rows($re)==0)
{
mysql_query("Insert Into clients Set $query");
$msg = "<span class='error' style=\"color:green;\"><b>Data Successfully Imported Into The Database</b></span>";
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Data Already Existed in Database</b></span>";
}
}
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Please select fields!</b></span>";
}
}
if(file_exists($_SESSION["FILENAME"]))
unlink($_SESSION["FILENAME"]);
}
}
}
if(isset($_POST['submt']))
{
if($_FILES['filename']["name"]=="")
$err = "<span class='error'>".IMPORT_PLEASE."</span>";
elseif(substr(strrev($_FILES['filename']["name"]),0,3)!="vsc")
$err = "<span class='error'>".IMPORT_INVALID."</span>";
else
{
$_SESSION['cltype']=$_POST['cltype'];
set_time_limit(0);
if(file_exists($Upload_Path.$_FILES['filename']["name"]))
$filename = GetRandomString(6).$_FILES['filename']["name"];
else
$filename = $_FILES['filename']["name"];
if(move_uploaded_file($_FILES['filename']["tmp_name"],$Upload_Path.$filename))
{
$upload_file = $Upload_Path.$filename;
$_SESSION["FILENAME"] = $upload_file;
}
else
$err = "<span class='error'>".IMPORT_FAIL."</span>";
set_time_limit(30);
}
}
?>
<script>
function Check_All2(obj,arr)
{
if(obj.checked)
{
var i=document.cfrm.elements.length;
var j;
for(j=0;j<i;j++)
{
if(document.cfrm.elements[j].name==arr)
document.cfrm.elements[j].checked=true;
}
}
else
{
var k=document.cfrm.elements.length;
var l;
for(l=0;l<k;l++)
{
if(document.cfrm.elements[l].name==arr)
document.cfrm.elements[l].checked=false;
}
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('#cfrm').submit(function(event) {
colums = jQuery('select.colum');
var arr = new Array();
var h_status=false;
colums.each(function()
{
var el=jQuery(this).val();
if(el!='')
{
h_status=true;
if(jQuery.inArray(el,arr)>-1)
{
event.preventDefault();
jQuery(this).css("border","2px solid red");
alert("Duplicated Fields!");
jQuery(this).focus();
return false;
}
else
{
arr.push(el);
jQuery(this).css("border","");
}
}
});
chks = jQuery('.chk');
chks.each(function()
{
if (jQuery(this).is(':checked'))
{
h_cols=jQuery('#h_cols').val();
var mand=1;
for(var k=0; k<=h_cols; k++)
{
colum_id='#colum_'+k;
colum_value=jQuery(colum_id).val();
flel_object=jQuery('#row_'+k+'_'+jQuery(this).val());
flel_value=jQuery('#row_'+k+'_'+jQuery(this).val()).val();
if(colum_value=='full_name')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Full Name');
flel_object.focus();
return false;
}
}
else if(colum_value=='aaa')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Email');
flel_object.focus();
return false;
}
}
}
}
});
if(!h_status)
{
event.preventDefault();
alert('Select Any Field To Insert!');
return false;
}
});
});
</script>
<script type="text/javascript" src="ajaxsublistgenerator.js"></script>
<table class="sub" height="20px" width="100%" border="0" cellpadding="0" cellspacing="0" align="center"></table>
<table width="99%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td>
<fieldset>
<?
if($upload_file=="")
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CSV;?></legend>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<table width="45%" border="0" cellpadding="4" cellspacing="4" align="center">
<?
if($err!="" || $msg!="")
{
?>
<tr><td colspan="2"><?=($err!="") ? $err : $msg?></td></tr>
<?
}
?>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_FILE;?></b></td>
<td width="70%" align="left" valign="middle">
<input name="filename" id="filename" type="file" size="25" />
</td>
</tr>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_SECTION;?></b></td>
<td width="70%" align="left" valign="middle">
<select name="cltype" id="cltype">
<option value="Client">Clients</option>
<option value="prospect">Leads</option>
<option value="Contacts">Contacts</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td align="left" valign="middle">
<input name="submt" type="submit" value="<?=IMPORT_UPLOAD;?>">
</td>
</tr>
</table>
</form>
<script>document.getElementById("filename").focus();</script>
<?
}
else
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CONTENT;?></legend>
<form name="cfrm" id="cfrm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_type" id="frm_type" value="custom">
<div style="overflow:auto;width:100%;">
<table border="0" cellspacing="4" cellpadding="4" align="center" width="100%">
<tr>
<td width="5%" align="center">
<input onClick="javascript:Check_All2(this,'chk[]')" type="checkbox" checked="checked">
</td>
<td width="10%" align="center"><b><?=IMPORT_CAT;?></b></td>
<?php
$fd_header = fopen ($upload_file, "r");
$buffer_header = fgetcsv($fd_header, 100000, ',');
//print_r(count($buffer_header));
for($r=0; $r<count($buffer_header);$r++)
{
?>
<td width="10%" align="center">
<select class="colum" name="colum_<?php echo $r;?>" id="colum_<?php echo $r;?>">
<option value="">--Select Field--</option>
<option value="full_name">Name</option>
<option value="address">Address</option>
<option value="city">City</option>
<option value="state">Province</option>
<option value="zip">Code Postal</option>
<option value="country">Country</option>
<option value="home_phone">Tel(Home)</option>
<option value="work_phone">Tel(Work)</option>
<option value="cell_phone">Tel(Mobile)</option>
<option value="email">Email</option>
<option value="conjoint">Joint</option>
<option value="notes">Notes</option>
<option value="birthday">Birthday</option>
</select><input type="hidden" id="h_cols" name="h_cols" value="<?php echo count($buffer_header); ?>" />
</td>
<?php } ?>
</tr>
<?
$fd = fopen ($upload_file, "r");
$i=1;
while (!feof ($fd))
{
$buffer_header = fgetcsv($fd, 100000, ',');
?>
<tr>
<td align="center"><input class="chk" type="checkbox" value="<?=$i?>" name="chk[]" checked="checked" /></td>
<td align="left" ><?php $sql_cat_names = mysql_query("select * from clients_cat where user_id='".$_SESSION['user_id']."' order by cat_name") ;?>
<select class="ann_select" name="cat_id<?=$i?>" id="cat_id<?=$i?>">
<?php while($row_cat_names = mysql_fetch_array($sql_cat_names)){?>
<option value="<?=$row_cat_names['id']?>"><?=$row_cat_names['cat_name']?></option>
<?php } ?>
</select>
</td>
<?php
for($v=0; $v<count($buffer_header);$v++)
{
?>
<td align="center">
<input type="text" value="<?=$buffer_header[$v]?>" name="row_<?=$v?>_<?=$i?>" id="row_<?=$v?>_<?=$i?>" />
</td>
<?php } ?>
</tr>
<?php
$i++;
unset($buffer_header);
}
fclose ($fd);
?>
<tr>
<td colspan="7" align="center">
<input name="Submit" id="Submit" type="submit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
<?php
}
?>
</fieldset>
</td>
</tr>
</table>
You may insert multiple values in an only insert, and reduce the DDBB load.
In your PHP code, you receive the values, and make a foreach to insert each row one by one. What you should have to do is change your one by one insert to a multiple to one insert.
You're doing:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2');
INSERT INTO table (field1, field2) VALUES ( 'value3', value4');
INSERT INTO table (field1, field2) VALUES ( 'value5', value6');
That gives you 3 connection to database, 3 inserts. Your query should be:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2'), ('value3, 'value4'), ('value5', 'value6');
That gives you 1 connection to database, 3 inserts. Same result, less load.
UPDATE
To accomplish it in your code, you must create a string inside of your foreach with the data you want to insert: Validate the fields, create the string, and then insert them into the DDBB with an insert sentence that is out of your foreach. It's going to be a mess if I try to do it without running the script to check everything goes well, so I can only point you in the way to do the job.
I am new to Javascript, Please help to me solve this issue Javascript experts.
I have a registration form that have these above fields. In this form, When I click "Add new registration line", it will insert new insert field like as above. From these, I want to add these hightlighted input fields values and display it in html table. When I check the checkbox, the values should be displayed in invoicable field, Likewise when I uncheck the checkbox, the values should be displayed in Non-Voicable field. I mean the sum of checked values should be displayed in Invoicable field and the sum of unchecked values should be displayed in Non-invoicable field.
This is the code part of the issue i am trying:
<script type="text/javascript">
$(function() {
var i = 8 + 1;
$('input#add').click(function() {
//store in hidden value for total row
document.getElementById("consinvoice").value=i;
$("<span style='margin-left:126px;'>: <select name='RegistrationType_"+i+"' id='RegistrationType_"+i+"' onchange=\"register('Invoicable_"+i+"',this.value,ConsultancyHours_"+i+".value)\"><option value='CH'>Consultancy Hours</option><option value='LH'>Lunch Hours</option><option value='TH'>Transportation Hours</option><option value='OH'>Other Hours</option></select> <input name='ConsultancyHours_"+i+"' type='text' id='ConsultancyHours_"+i+"' size='5' onkeyup=\"invotable(this.id,this.value);\" /><label for='Hourprice'> Std. Hourprice</label> <input name='Hourprice_"+i+"' type='text' id='Hourprice_"+i+"' size='5' /> <label for='Hourprice'>- Discount Hourprice</label> <input name='Hourprice2_"+i+"' type='text' id='Hourprice2_"+i+"' size='5' /><br /><span style='margin-left:652px;'><input name='Invoicable_"+i+"' type='checkbox' id='Invoicable_"+i+"' checked='checked' onclick=\"register('Invoicable_"+i+"',RegistrationType_"+i+".value,ConsultancyHours_"+i+".value)\" /><label for='Invoicable'> Invoicable</label></span><br /></span>").appendTo('dd');
i++;
});
});
</script>
<script type="text/javascript">
//register('Invoicable_"+i+"',RegistrationType_"+i+".value,this.value);
function invotable(getid,getvalue){
var getinvoicetbl = 'invoice_cons';
var previnvoice = document.getElementById(getinvoicetbl).innerHTML;
var dgetid = getid.split("_");
var getcount = document.getElementById("consinvoice").value;
//alert(getcount);
totalterm =0;
for (j=8;j<=getcount;j++)
{
totalterm += parseInt(document.getElementById("ConsultancyHours_"+j).value);
//register('Invoicable_'+j,document.getElementById("RegistrationType_"+j).value,document.getElementById("ConsultancyHours_"+j).value);
}
document.getElementById(getinvoicetbl).innerHTML = totalterm;
}
function register(getvoice,gettype,getvalue){
//alert(getvoice);
var checkbox = document.getElementById(getvoice).checked;
var getinvoice = 'invoice_cons';
var getnovoice = 'ninvoice_cons';
switch (gettype)
{
case "CH":
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("totinvoice").value - getvalue;
alert(document.getElementById("totinvoice").value);
alert(document.getElementById(getnovoice).innerHTML);
} else {
alert(document.getElementById("totinvoice").value);
document.getElementById(getnovoice).innerHTML = parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
break;
case "LH":
if(checkbox ==true ){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
default:
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
}
}
</script>
<input type="hidden" name="consinvoice" id="consinvoice" value="8" />
<input type="hidden" name="totinvoice" id="totinvoice" value="0" />
<input type="hidden" name="fromtinvoice" id="fromtinvoice" value="0" />
<td width="220">
<span id="insert_table">
<table class="" id="invtable" width="150" border="1">
<tr>
<td align="right">
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Non-Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Total
</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Consultancy</td>
<td align="right" id="invoice_cons">-</td>
<td align="right" id="ninvoice_cons">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Transportation</td>
<td align="right" id="invoice_trans">-</td>
<td align="right" id="ninvoice_trans">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Lunch</td>
<td align="right" id="invoice_lun">-</td>
<td align="right" id="ninvoice_lun">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Total</td>
<td align="right" id="invoice_tot">-</td>
<td align="right" id="ninvoice_tot">-</td>
<td align="right" >-</td>
</tr>
<tr>
</table>
</span>
</table>
<p>
<label for="RegistrationType">
Type
</label>
<span style="margin-left:92px;">
: <select name="RegistrationType_8" id="RegistrationType_8" onchange="register('Invoicable_8',this.value,ConsultancyHours_8.value)">
<option value="CH">Consultancy Hours</option>
<option value="LH">Lunch Hours</option>
<option value="TH">Transportation Hours</option>
<option value="OH">Other Hours</option>
</select>
<input name="ConsultancyHours_8" type="text" id="ConsultancyHours_8" size="5" onkeyup="invotable(this.id,this.value); " />
<label for="Hourprice">
Std. Hourprice
</label>
<input name="Hourprice_8" type="text" id="Hourprice_8" size="5" />
<label for="Hourprice">
- Discount Hourprice
</label>
<input name="Hourprice2_8" type="text" id="Hourprice2_8" size="5" />
<input name="Invoicable_8" type="checkbox" id="Invoicable_8" onclick="register('Invoicable_8',RegistrationType_8.value,ConsultancyHours_8.value)" checked="checked" />
<label for="Invoicable">
Invoicable
</label>
<dd id="insert_row">
</dd>
</span>
</p>
<p>
<span style="margin-left:132px;">
<input type="button" id="add" value="Add new registration line" />
</span>
</p>
<div style="margin-left:324px;">
</div>
<br />
<p>
<span style="margin-left:132px;">
<input type="submit" name="Submit" id="Submit" value="Save registration" />
</span>
</p>
You can create a function to add new row dynamically and other function to calculate the hour by scaning the form, then when the window is loaded, call the add row function to start. There is the source code that I created:
<!DOCTYPE html>
<style>
body{margin:0}
body,th,td{font:16px Arial, Helvetica, sans-serif}
table{border-spacing:0;border-collapse:collapse;table-layout:fixed}
th,td{white-space:nowrap;overflow:hidden}
th{font-weight:700}
#invtable{width:500px;margin:10px auto;border:1px solid #000}
#invtable th, #invtable td{border:1px solid #000}
#registrationForm{width:100%}
#registrationForm td{text-align:center}
#registrationForm input[type="number"]{width:140px}
</style>
<table id="invtable" width="150">
<tr>
<th>Type</th>
<th>Invoicable</th>
<th>Non-Invoicable</th>
<th>Total</th>
</tr>
<tr id="consultancy">
<th>Consultancy</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="transportation">
<th>Transportation</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="lunch">
<th>Lunch</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="other">
<th>Other</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="registrationForm"></table>
<p><input type="button" id="addNewRegistrationLine" value="Add new registration line"></p>
<p><input type="submit" id="saveRegistration" value="Save registration"></p>
<script>
var doc = document;
function calculateHour() {
var registrationForm = doc.getElementById('registrationForm');
var registrationFormRows = registrationForm.rows
var typeValue = {'CH' : [0,0], 'LH' : [0,0], 'TH' : [0,0], 'OH' : [0,0]};
for (var i = 0, registrationFormRowsLength = registrationFormRows.length, typeSelect, inputs, hourInput, isInvoicable; i < registrationFormRowsLength; ++i) {
typeSelect = registrationFormRows[i].getElementsByTagName('SELECT')[0];
inputs = registrationFormRows[i].getElementsByTagName('INPUT');
hourInput = inputs[0];
isInvoicable = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[typeSelect.value][isInvoicable] += hourInput.value - 0;
}
var total = [0, 0]
var consultancyCells = doc.getElementById('consultancy').cells;
consultancyCells[1].innerHTML = typeValue['CH'][0];
total[0] += typeValue['CH'][0];
consultancyCells[2].innerHTML = typeValue['CH'][1];
total[1] += typeValue['CH'][1];
consultancyCells[3].innerHTML = typeValue['CH'][0] + typeValue['CH'][1];
var transportationCells = doc.getElementById('transportation').cells;
transportationCells[1].innerHTML = typeValue['TH'][0];
total[0] += typeValue['TH'][0];
transportationCells[2].innerHTML = typeValue['TH'][1];
total[1] += typeValue['TH'][1];
transportationCells[3].innerHTML = typeValue['TH'][0] + typeValue['TH'][1];
var lunchCells = doc.getElementById('lunch').cells;
lunchCells[1].innerHTML = typeValue['LH'][0];
total[0] += typeValue['LH'][0];
lunchCells[2].innerHTML = typeValue['LH'][1];
total[1] += typeValue['LH'][1];
lunchCells[3].innerHTML = typeValue['LH'][0] + typeValue['LH'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OH'][0];
total[0] += typeValue['OH'][0];
otherCells[2].innerHTML = typeValue['OH'][1];
total[1] += typeValue['OH'][1];
otherCells[3].innerHTML = typeValue['OH'][0] + typeValue['OH'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRegistrationLine() {
var registrationForm = doc.getElementById('registrationForm');
var row = registrationForm.insertRow(registrationForm.rows.length);
var typeSelectCell = row.insertCell(0);
var type = [['CH', 'Consultancy Hours'], ['LH', 'Lunch Hours'], ['TH', 'Transportation Hours'], ['OH', 'Other Hours']];
var typeSelect = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
typeSelect.appendChild(option);
}
typeSelect.onchange = calculateHour;
var typeLabel = doc.createElement('LABEL');
typeLabel.innerHTML = 'Type';
typeLabel.appendChild(typeSelect);
typeSelectCell.appendChild(typeLabel);
var hourInput = doc.createElement('INPUT');
hourInput.type = 'number';
hourInput.onkeyup = calculateHour;
typeSelectCell.appendChild(hourInput);
var hourPriceInputCell = row.insertCell(1);
var hourPriceInput = doc.createElement('INPUT');
hourPriceInput.type = 'number';
var hourPriceLabel = doc.createElement('LABEL');
hourPriceLabel.innerHTML = 'Std. Hourprice';
hourPriceLabel.appendChild(hourPriceInput);
hourPriceInputCell.appendChild(hourPriceLabel);
var discountInputCell = row.insertCell(2);
var discountInput = doc.createElement('INPUT');
discountInput.type = 'number';
var discountLabel = doc.createElement('LABEL');
discountLabel.innerHTML = '- Discount Hourprice';
discountLabel.appendChild(discountInput);
discountInputCell.appendChild(discountLabel);
var invoicableCheckBoxCell = row.insertCell(3);
var invoicableCheckBox = doc.createElement('INPUT');
invoicableCheckBox.type = 'checkbox';
invoicableCheckBox.onclick = calculateHour;
var invoicableLabel = doc.createElement('LABEL');
invoicableLabel.appendChild(invoicableCheckBox);
invoicableLabel.appendChild(document.createTextNode('Invoicable');
invoicableCheckBoxCell.appendChild(invoicableLabel);
}
doc.getElementById('addNewRegistrationLine').onclick = addNewRegistrationLine;
window.onload = function() {
addNewRegistrationLine();
};
</script>
Live example
since it appears that you are using the Jquery Framework you can use the template feature which will allow you to use your javascript data and create html from it, I personally have not used it though.But since you also tagged this with PHP. Why not just do it in PHP?
For Example:
$formData[];
foreach($_POST AS $field => $value) {
$formData[$field] = $value;
}
Then all your data is in an array and much easier to work with. Just make sure to put in the form tag and use the method=“post” attribute.