How to Save multiple data array in database - javascript

I create an addline array button that creates multiple array fields my problems is that I can't save the data that inserted to the fields.
JavaScript
var MaxInputs = 3; //maximum input boxes allowed
var InputsWrapper = $("");
var addlines = 1;
var FieldCount = 1; //to keep track of text box added
function AddORDeleteLines(obj,type){
type=type+'';
var objtype=obj.id+'';
if(type==="add"){
if(objtype==='AddMoreLines'){
if(addlines<=MaxInputs){
FieldCount++;
InputsWrapper = $("#ADD_LINE-txtEmployee-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="text" name="txtEmployee" size="30"/>'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtDate-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="date" name="txtDate"/>'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtTimeFrom-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="time" name="txtTimeFrom" />'+
'</div>');
InputsWrapper = $("#ADD_LINE-txtTimeTo-div");
$(InputsWrapper).append('<div class="class-div_'+FieldCount+'">'+
'<input type="time" name="txtTimeTo" />'+
'<input type="button" onClick="AddORDeleteLines(this,'+"'delete'"+')" id="removeButton_'+FieldCount+'" value="x" class="removeLines"/>'+
'</div>');
addlines++;
}
}
}
else if(type==="delete"){
var parentobj = $("#"+obj.id).parent('div');
//$(parentobj).parent('div').remove();
var objclass = $("#"+obj.id).parent('div').attr("class")+'';
objtype = $("#"+obj.id).attr("class")+'';
if(objtype==='removeLines'){
addlines--;
}
$("div").remove('.'+objclass);
return false;
}}
View
<table>
<tr>
<td>
<div id="ADD_LINE-txtEmployee-div">
<input type="text" id="txtEmployee" name="txtEmployee" size="30"/>
</div>
</td>
<td>
<div id="ADD_LINE-txtDate-div">
<div>
<input type="date" id="txtDate" name="txtDate" />
</div>
</div>
</td>
<td>
<div id="ADD_LINE-txtTimeFrom-div">
<div>
<input type="time" id="txtTimeFrom" name="txtTimeFrom" />
</div>
</div>
</td>
<td>
<div id="ADD_LINE-txtTimeTo-div">
<div>
<input type="time" id="txtTimeTo" name="txtTimeTo" />
<input type="button" id="AddMoreLines" onclick="AddORDeleteLines(this,'add')" value="ADD LINE" />
</div>
</div>
</td>
</tr>
Controller
public function SaveOvertime(){
$this->load->library('form_validation');
$this->form_validation->set_rules('txtEmployee[]', 'Employee', 'required');
$this->form_validation->set_rules('txtTimeFrom[]', 'Time From', 'required');
$this->form_validation->set_rules('txtTimeTo[]', 'Time to', 'required');
$this->form_validation->set_rules('txtDate[]', 'Date', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('error_overtime');
}
else
{
$this->load->model('dtr_model');
$this->dtr_model->saveovertime();
$this->load->view('success_overtime');
}
MODEL
function saveovertime(){
$value = array(
'EMPLOYEE'=>$this->input->post('txtEmployee[]'),
'TIME_FROM'=>$this->input->post('txtTimeFrom[]'),
'TIME_TO'=>$this->input->post('txtTimeTo[]'),
'DATE'=>$this->input->post('txtDate[]'));
$query = $this->db->insert('dtr_timerecord_overtime_line',$value);}

I think you need to store these multiple values of each field by using json_encode() or serialize() functions of php. Replace your saveovertime() function with below function:
function saveovertime(){
$value = array(
'EMPLOYEE'=>json_encode($this->input->post('txtEmployee')),
'TIME_FROM'=>json_encode($this->input->post('txtTimeFrom')),
'TIME_TO'=>json_encode($this->input->post('txtTimeTo')),
'DATE'=>json_encode($this->input->post('txtDate')));
$query = $this->db->insert('dtr_timerecord_overtime_line',$value);}

Related

Is there any way to insert multiple data in a field of table and one specific data has different value on its field? Codeigniter

I am making a quiz app and one question must be correct. I can already insert multiple data in my table, the problem that i have is, I have a one specific choice or answer that must be different from the others.
A screenshot of the app and what im trying to do
Here's what my table looks like
table answers
id | answer | correct
1 | Apple | 1
2 | Mango | 0
3 | Melon | 0
1, indicate for correct answer and 0 indicate for incorrect.
So here is my Model.
I tried to make an attempt to fetch the radio button value which is the 1 value and insert it to the database but the result was, IF I add another data or multiple data. Index 0 or the first data was the only data that can be inserted. I CANNOT choose what radio button i can check only the FIRST button I can check.
// Insert questions
$field_question = array(
'question'=>$this->input->post('question'),
);
$this->db->insert('questions', $field_question);
// Insert Answers
$data_answer = $this->input->post('choice[]');
$data_is_correct = $this->input->post('checkChoice[]');
$value = array();
for($i = 0; $i < count($data_answer); $i++) {
$value[$i] = array(
'answer' => $data_answer[$i],
'correct' => $data_is_correct[$i],
'question_id' => $this->db->insert_id(),
);
}
$this->db->insert_batch('answers', $value);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
Problem of my table if I add 3 new data
id | answer | correct
1 | Apple | 1
2 | Mango | 0
3 | Melon | 0
* New 3 Data Inserted
4 | Orange | 1
5 | Tomato | 0
6 | Grapes | 0
I cannot makeTomato or Grapes to be my answer or make it as value number 1 only Orange or the first added data.
VIEW
So here is my radio button
<div class="form-check">
<input class="form-check-input" type="radio" name="checkChoice[]" id="checkChoice" value="1" checked />
<label class="form-check-label" for="exampleRadios1">
Make this as an Answer
</label>
</div>
And my form.
<form method="post" id="myForm" action="<?php echo base_url(); ?>posts/addQuestion">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Question</span>
</div>
<input type="text" placeholder="Enter your Question" name="question" id="question" class="form-control" required />
</div>
<hr>
<h5>Create Choices: </h5>
<div class="input-group input-group-sm mb-3">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="hidden" name="choiceHid[]" value="0" /></td>
<td><input type="text" name="choice[]" id="choice" placeholder="Enter your Choice" class="form-control" /> </td>
<td><button type="button" name="add" id="add" class="btn btn-success"><span class="iconify" data-icon="ant-design:plus-circle-outlined" data-inline="false"></span> Add Response </button></td>
<td>
<div class="form-check">
<input class="form-check-input" type="radio" name="checkChoice[]" id="checkChoice" value="1" checked />
<label class="form-check-label" for="exampleRadios1">
Make this as an Answer
</label>
</div>
</td>
</tr>
</table>
</div>
</div>
<hr>
<input type="button" id="btnSave" class="btn btn-block btn-info" value="Submit" />
</form>
Script
<script>
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}
swal("Success!", "You created a Question!", "success");
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
</script>
Dynamic Field Script
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append(
'<tr id="row'+i+'">'+
'<td><input type="hidden" name="choiceHid[]" value="0" /></td>'+
'<td><input type="text" name="choice[]" placeholder="Enter your Choice" class="form-control" /></td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove"><span class="iconify" data-icon="dashicons:remove" data-inline="false"></span></button></td>'+
'<td>'+
'<div class="form-check">'+
'<input class="form-check-input" type="radio" name="checkChoice[]" id="checkChoice" value="1" />'+
'<label class="form-check-label" for="exampleRadios1">'+
'Make this as an Answer'+
'</label>'+
'</div>'+
'</td>'+
'</tr>'
);
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
Dynamic Field Script
make variable val as a value of checkChoice like following...
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
var val =i;
i++;
$('#dynamic_field').append(
'<tr id="row'+i+'">'+
'<td><input type="hidden" name="choiceHid[]" value="0" /></td>'+
'<td><input type="text" name="choice[]" placeholder="Enter your Choice" class="form-control" /></td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove"><span class="iconify" data-icon="dashicons:remove" data-inline="false"></span></button></td>'+
'<td>'+
'<div class="form-check">'+
'<input class="form-check-input" type="radio" name="checkChoice" id="checkChoice" value="'+val+'" />'+
'<label class="form-check-label" for="exampleRadios1">'+
'Make this as an Answer'+
'</label>'+
'</div>'+
'</td>'+
'</tr>'
);
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
View
asign initial value of checkChoice as 0 like following
<div class="form-check">
<input class="form-check-input" type="radio" name="checkChoice" id="checkChoice" value="0" checked />
<label class="form-check-label" for="exampleRadios1">
Make this as an Answer
</label>
</div>
// Insert Answers
$data_answer = $this->input->post('choice[]');
$data_is_correct = $this->input->post('checkChoice');
$value = array();
for($i = 0; $i < count($data_answer); $i++) {
if($data_is_correct == $i) {
$correct = 1;
} else {
$correct = 0;
}
$value[$i] = array(
'answer' => $data_answer[$i],
'correct' => $correct,
'question_id' => $this->db->insert_id(),
);
}

unable to get check boxes value from table

I am not able to get the checkboxes values from checkboxes to Firebase.
How will I be able to get each value from each box from each row?
Table:
Check boxes:
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
Table
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
full form
<div class="form-popup" id="myFormDetails">
<div class="shipDetailsRequest">
<form action="" method="post" class="form-container" >
<button type="button" onclick="closeForm()" id="close">x</button>
<input name="RR" type="RRField" id="date" disabled>
<input name="RR" type="RRField" id="RRField" placeholder="RR Field" disabled>
<p>Customer Details</p>
<input onclick="sampleFunction()" type="number1" placeholder="Customer Account Number" name="customerAccountField" id="customerAccountField" required>
<input type="number1" placeholder="Customer Name" name="customerNameField" id="customerNameField" disabled>
<p>Shipper Details</p>
<input type="number1" placeholder="Shipper Name" name="senderName" id="shipperName" required>
<textarea name="collectionAddress" placeholder="Collection Address...?" id="collectionAddress"></textarea>
<p>Shipment Details</p>
<input type="text" placeholder="Enter Origin" name="shptOrigin" id="shipmentOrigin" maxlength = "3" required>
<input type="text" placeholder="Enter Destination" name="shptDest" id="shipmentDest" maxlength = "3" required>
<input type="number" placeholder="Enter Weight" name="shptWeight" id="shptWeight" required>
<input type="number" placeholder="Enter Pieces" name="shptPieces" id="shptPieces" required>
<input type="number1" placeholder="Enter Dimensions" name="shptDimensions" id="shipmentDimensions" >
<select placeholder="Choose Type" name="shptStack" id="shptStack" required>
<option value="Stackable">Stackable</option>
<option value="Nonstackable">Nonstackable</option>
</select>
<select placeholder="Choose Desk" name="Desk" id="ChooseDesk" required>
<option value="KSA">KSA Desk</option>
<option value="DHA">DHA Desk</option>
<option value="RUH">RUH Desk</option>
<option value="JED">JED Desk</option>
</select>
<p>Comment</p>
<textarea name="comment" placeholder="Other Details...?" id="commentField"></textarea>
<div class="mainDiv" align="center" >
<input type="file" id="fileButton" />
<progress id="uploader" value="0" max="100" style="max-width: 128px;">0%</progress>
</div>
<!-- <button id="submitBtn" onclick="ActionData()">Next</button> -->
<button id="submitBtn" onclick="ActionData()">Next</button>
</form>
</div>
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
Full JavaScript
var DateText = document.getElementById("date");
var RRText = document.getElementById("RRField");
var CustAccText = document.getElementById("customerAccountField");
var CustNameText = document.getElementById("customerNameField");
var ShipperNameText = document.getElementById("shipperName");
var CollectionAddressText = document.getElementById("collectionAddress");
var ShipmentOrgText = document.getElementById("shipmentOrigin");
var ShipmentDestText = document.getElementById("shipmentDest");
var ShipmentweightText = document.getElementById("shptWeight");
var ShipmentPiecesText = document.getElementById("shptPieces");
var ShipmentDimensionsText = document.getElementById("shipmentDimensions");
var ShptStackText = document.getElementById("shptStack");
var ChooseDeskText = document.getElementById("ChooseDesk");
var CommentText = document.getElementById("commentField");
var ShipmentOriginValues = ShipmentOrgText.value;
ShipmentOriginValues = "All";
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
if (ShipmentOrgText.value != null)
{
var rootRefReAgents = firebase.database().ref().child("AgentsContact").child(ShipmentOriginValues);
rootRefReAgents.on("child_added", snap =>{
var AgentEmail = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
});
}
function ActionData()
{
//setting up values from Text Fields
var DateValue = DateText.value;
var RRValue = RRText.value;
var CustAccountValue = CustAccText.value;
var CustNameValue = CustNameText.value;
var ShipperNameValue = ShipperNameText.value;
var CollectionAddressValues = CollectionAddressText.value;
ShipmentOriginValues = ShipmentOrgText.value;
var ShipmentDestValues = ShipmentDestText.value;
var ShipmentweightValues = ShipmentweightText.value;
var ShipmentPiecesValues = ShipmentPiecesText.value;
var ShipmentDimensionsValues = ShipmentDimensionsText.value;
var ShptStackValues = ShptStackText.value;
var ChooseDeskValues = ChooseDeskText.value;
var CommentValues = CommentText.value;
var FirebaseRef = firebase.database().ref("Requests").child(RRValue);
if(RRValue && ShipmentOriginValues && ShipmentDestValues && CustAccountValue == null)
{
window.alert("Need More details to upload")
}
else
{
FirebaseRef.child("Date").set(DateValue);
FirebaseRef.child("RR").set(RRValue);
FirebaseRef.child("Customer Account").set(CustAccountValue);
FirebaseRef.child("Customer Name").set(CustNameValue);
FirebaseRef.child("Shipper Name").set(ShipperNameValue);
FirebaseRef.child("Collection Address").set(CollectionAddressValues);
FirebaseRef.child("Origin").set(ShipmentOriginValues);
FirebaseRef.child("Destination").set(ShipmentDestValues);
FirebaseRef.child("Weight").set(ShipmentweightValues);
FirebaseRef.child("Pieces").set(ShipmentPiecesValues);
FirebaseRef.child("Dimensions").set(ShipmentDimensionsValues);
FirebaseRef.child("Stack").set(ShptStackValues);
FirebaseRef.child("Desk").set(ChooseDeskValues);
FirebaseRef.child("Comment").set(CommentValues);
FirebaseRef.child("Status").set("Pending");
//Uploading
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = firebase.storage().ref('img/'+RRValue+'/'+file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
uploader.value = percentage;
}, function error(err) {
},function complete() {
});
});
}
}
I need to check boxes from the table and get their values back to Firebase when form is submitted.
You could specify an id or name for each input and then retrieve their value when you submit the form.
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><input type=\"checkbox\" id=\""+AgentEmail+"\" Value =\"Agent\"></Input></td></tr>")
var agents = ... //Get your agents list from firebase
$form.on('submit', function(){
agents.forEach(function(agent){
if($('#'+agent.email).prop('checked'){
//do something
}
})
})
If your code is working, you can ckeck if a checkbox is checked with:
/* jQuery */
if ($('#check_id').is(":checked"))
{
// checkbox is checked
}
you can also use:
/* jQuery */
$("#idOfCurrentRow").children()."input[type='checkbox']") is(":checked")
If you prefer pure JavaScript:
/* pure JavaScript*/
if(document.getElementById("idOfYourCheckbox").checked) {
...
}
or
if (document.getElementByName("nameOfYourCheckbox").checked) {
.....
}

Saving form data into dynamic form when hitting back or refreshing page

Right now I have code to dynamically add input fields to my form. I want to be able to submit the data and go to the next page but if someone decides to go back, the newly made input fields would still be there with the data. The way I have it set up now is to echo onto the input fields which works with the first two but not the third.
When I hit back, I get this:
Here is my code:
<h2>Enter Beneficiaries for Tangible Personal Property:</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="input_fields_container">
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" ></input></td>
</tr>
</table>
</div>
<p style="color:red;"></p>
<h3>Enter Contingent Beneficiary: </h3>
Name:<input type="text" name="conben" value="<?php echo $_SESSION['conben'];?>" >
<br><br>
<button type="button" name="back" value="back" onclick="location.href='county.php'">Back</button>
<input type="submit" name="submitform" value="Next"></input>
<button type="button" name="download" onclick="location.href='downloadAdd.php'">Download will</button>
</form>
<script>
//script to add/remove fields
$(document).ready(function () {
var getControl=getCookie("countControls1");
var max_fields_limit = 2; // Set limit for maximum input fields
var x = 0; // Initialize counter for text box
for(var i=1; i<=getControl; i++) {
console.log(i);
addControls();
}
$('.add_more_button').click(function (e) { // Click event to add more fields
addControls();
});
function addControls()
{
console.log(x);
if (x < max_fields_limit ) {
x++; // Increment counter
setCookie("countControls1",x,100);
$('.input_fields_container').append('<div><tr id="row'+x+'"><td> Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['1'];?>" class="form-control name_list" /></td><td>&nbspPercentage of tangible personal property:<input type="number" min="0" max="100" style="width: 40px" name="percent[]" value="<?php echo $_SESSION['percent']['1'];?>" class="form-control name_list" /></td><td>Remove</td></tr>');; // Add input field
}
else if (x==2){
$("p").text("*Only 3 tangible beneficiaries are allowed.");
}
}
$('.input_fields_container').on("click", ".remove_field", function (e) { // User click on remove text links
$(this).parent('div').remove();
x--;
$("p").text("");
setCookie("countControls1",x,100);
});
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
$("#div1").html("Add cookie = ",getCookie(cname));
}
function getCookie(cname)
{
console.clear();
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
//console.log(cname);
//console.log(decodedCookie);
console.log(ca);
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
console.log(c.substring(name.length, c.length));
return (c.substring(name.length, c.length));
}
}
return "";
}
});
</script>
Is there anyway to achieve this in this way or do I need to implement something else?
You can just write the fields back using a loop because presumably you have the two arrays in your session. You should also use empty() or isset() to check if the session arrays exist first otherwise you will end up with warnings about undefined keys and such:
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben']['0'];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $_SESSION['percent']['0'];?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
<td><input type="button" name="add" id="add" class="add_more_button" value= "Add Another" /></td>
</tr>
<?php
# Remove the first keys since you already used them above
unset($_SESSION['percent'][0],$_SESSION['ben'][0]);
# Just do a normal loop to create any remaining values
foreach($_SESSION['percent'] as $key => $value): ?>
<tr>
<td>Name:<input type="text" name="ben[]" value="<?php echo $_SESSION['ben'][$key];?>" class="form-control name_list" /></td>
<td>Percentage of tangible personal property:<input type="number" min="0" max="100" value="<?php echo $value; ?>" style="width: 40px" name="percent[]" class="form-control name_list" /></td>
</tr>
<?php endforeach ?>

Why dynamic input fields don't take values?

I am adding rows using java script functions by taking input and showing data into input text fields.
I am using this datepicker https://github.com/T00rk/bootstrap-material-datetimepicker.
When I input time the only first value of time is copied into input fields while rest two value are copied but time value is not copied.
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item quantity: <input type="text" name="add_qty" size="4" /> Item name: <input type="text" name="add_name" />Time:<input type="text" id="time" name="time" />
(This row will not be saved unless you click on "Add row" first)
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
When you generate dynamic textbox with id and with date picker so you need to call one function for init datepicker on that text like below
$('input').bootstrapMaterialDatePicker();
function addRow(frm)
{
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time'+rowNum+'" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
$('#time'+rowNum).bootstrapMaterialDatePicker();
}
In above function i add one id to time textbox and call bootstrap datepicker to init date on that textbox.
See working demo here
http://plnkr.co/edit/P0ZQsAjDJAXyJGs9kvT3?p=preview

How to insert values from dynamically added rows into database

I've been stuck on this for days. I really appreciate your help.
I'm working on a php form that generates dynamically added rows when
the user click the button ADD.
To save the values into the database, users must click the SUBMIT
button.
The problem that i'm facing is that the database doesn't save the
values from the dynamic rows.
AUTOCOMPLETE & DYNAMIC ROWS
<script>
//autocomplete
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#ItemName" ).autocomplete({
source: "user/requisition_search.php",
minLength: 1,
select: function( event, ui )
{
$('#ItmId').val(ui.item.id);
$('#StkId').val(ui.item.stkId);
$('#ItmNameDis').val(ui.item.value);
$('#ItmUOM').val(ui.item.uom);
$('#ItmQty').val(ui.item.qty);
}
});
});
//dynamic rows
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row =
'<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId[]" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty[]" value="'+$("#ReqQty").val()+'"/></td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
});
</script>
HTML
<form name="jqtest" action="submit.php" method="post">
<label for="ItemName">Search : </label>
<input id="ItemName" size="50"/>
<label for="ItmId">Item Id </label>
<input name="ItmId" id="ItmId" readonly="readonly"/>
<label for="StkId">Stock Id </label></td>
<input name="StkId" id="StkId" readonly="readonly"/>
<label for="ItmNameDis">Item Name </label>
<input name="ItmNameDis" id="ItmNameDis" size="50" readonly="readonly"/></td>
<label for="ItmUOM">Unit Of Measurement </label>
<input name="ItmUOM" id="ItmUOM" readonly="readonly"/>
<td><label for="ItmQty">Quantity Available </label>
<input name="ItmQty" id="ItmQty" readonly="readonly"/>
<label for="ReqQty">Quantity </label>
<input name="ReqQty" id="ReqQty" onkeypress="return numbersOnly(event)" onkeyup="ItmQty_Availability()" disabled="disabled"/>
<p>
<input type="reset" name="reset" id="reset" value="RESET"/>
<input type="button" name="add" id="add" value="ADD"/>
</p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
<table id="dataTab" width="90%" style="display:none;" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Item ID</th>
<th>Stock ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity Available</th>
<th>Quantity Requested</th>
</tr>
</table>
<p> </p>
<p><input style="display:none;" type="submit" name="submit" id="submit" value="SUBMIT"/></p>
</form>
submit.php
<?php
$num = $_POST['rowcount'];
for($i=0;$i<$num;$i++)
{
$strStkId = "";
if(!empty($_POST)){
if(isset($_POST["StkId[]"])){
$strStkId = $_POST["StkId[]"];
}else{
echo "<font color=red>Enter the Stock Id</br></font>";
}
}
$strReqQty = "";
if(!empty($_POST)){
if(isset($_POST["ReqQty[]"])){
$strReqQty = $_POST["ReqQty[]"];
}else{
echo "<font color=red>Enter the Quantity</font>";
}
}
$tsql =
"INSERT INTO REQUISITION
(RequestQuantity, StockId)
VALUES
('$strReqQty','$strStkId')
";
$result = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if (!$result) {
die ('<script>
window.alert("Please enter the requisition details !")
window.location.href = "requisition.php"; </script>');
}
else
echo '<script>alert("Your Requisition is In Process"); </script>';
sqlsrv_close($conn);
}
?>
UPDATED
I've learnt that name="StkId" and name="StkId[]" clashes in the dynamic rows and the inputs.
So i've change into something like this :
var row = '<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId2" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty2" value="'+$("#ReqQty").val()+'"/></td></tr>';
Now the data are inserted into the database but IF the user enters more than one item, only one data is inserted into the database. What did i do wrong? I guess its at the submit.php part but i can't figure out why.
You won't get dynamically generated row values in $_POST on submitting the form because those are not at all form inputs but just displaying as row in a table. But you can achieve your functionality with the help of jQuery AJAX. On clicking the submit button, calls your submit.php using AJAX. The sample solution for how to retrieve values of those dynamically rows is given below. You can adapt this method for your requirement.
Main Page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Dynamic Rows</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row = '<tr class="dynamic" id="'+rowcount+'"><td>'+$("#itemid").val()+'</td><td>'+$("#itemname").val()+'</td><td>'+$("#uom").val()+'</td><td>'+$("#quantity").val()+'</td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
$("#submit").on("click",function(){
alert("submit");
var jsonObj = [];
i=0;
$("#dataTab tr.dynamic").each(function(){
var td = $(this).find('td');
itemId = td.eq(0).text();
itemName = td.eq(1).text();
uom = td.eq(2).text();
quantity = td.eq(3).text();
jsonObj.push({
itemId: itemId,
itemName: itemName,
uom: uom,
quantity: quantity,
});
});
var dataString = JSON.stringify(jsonObj);
$.ajax({
url: "submit.php",
type: "POST",
data: {json:dataString},
success: function(response){
alert(response);
}
});
});
});
</script>
</head>
<body>
<form name="jqtest" action="#">
Item ID : <input type="text" name="itemid" id="itemid"/><br/><br/>
Item name : <input type="text" name="itemname" id="itemname"/><br/><br/>
UOM : <input type="text" name="uom" id="uom"/><br/><br/>
Quantity : <input type="text" name="quantity" id="quantity"/><br/><br/>
<p> <input type="reset" name="reset" id="reset" value="RESET"/> <input type="button" name="add" id="add" value="ADD"/> </p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
</form>
<table id="dataTab" style="display:none;" border="1">
<tr>
<th>Item ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity</th>
</tr>
</table>
<p> <input style="display:none;" type="button" name="submit" id="submit" value="submit"/> </p>
</body>
</html>
submit.php
<?php
$arr = json_decode($_POST['json']);
for($i=0; $i<count($arr); $i++)
{
echo "Row ".$i."\n";
echo "itemId > ".$arr[$i]->itemId.", itemName > ".$arr[$i]->itemName.", uom > ".$arr[$i]->uom.", quantity > ".$arr[$i]->quantity."\n";
}
?>

Categories

Resources