I have added 2 dynamically added input fields in my application.
I want insert 2 field values in to 2 database column.
<div class="form-group ">
<div id="itemRows" class="col-md-12">
<div class="row">
<label>Earnings</label> <input type="text" name="add_qty" size="4" />
<label>Amount <input type="text" name="add_name" oninput="this.value
= this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
<button onclick="addRow(this.form);"><i class="menu-icon mdi mdi-
plus-circle"></i></button></div>
<script>
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Earnings: <input type="text"
name="qty[]" size="4" value="'+frm.add_qty.value+'"> Amount: <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 = '';
}
</script>
<script>
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</div>
</div>
I want to add all the earnings in earnings column and amount in amount column in database
First please correct your code In this naming is diffrent in both Html
<?php include 'config.php';
for($i = 0; $i < count($_POST['add_qty']); $i++)
{
$add_qty = mysqli_real_escape_string($connect, $_POST['add_qty'][$i]);
$add_name = mysqli_real_escape_string($connect, $_POST['add_name'][$i]);
if (empty(trim($add_qty))) continue;
$sql = "INSERT INTO earnigs_tbl(earnings, amount)
VALUES('$add_qty', '$add_name')";
mysqli_query($connect, $sql);
}
if(mysqli_error($connect))
{
echo "Data base error occure";
}
else
{
echo $i . " rows added";
}
?>
<div class="form-group ">
<div id="itemRows" class="col-md-12">
<div class="row">
<label>Earnings</label> <input type="text" name="add_qty" size="4" />
<label>Amount <input type="text" name="add_name" oninput="this.value
= this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
<button onclick="addRow(this.form);"><i class="menu-icon mdi mdi-
plus-circle"></i></button></div>
<script>
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Earnings: <input type="text"
name="add_qty[]" size="4" value="'+frm.add_qty.value+'"> Amount: <input
type="text" name="add_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 = '';
}
</script>
<script>
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
</div>
</div>
Related
I got this code somewhere and modified it according to my need, but it is working only on one, first section. It should work anytime I add multiple items to my order but it is not working as expected.
Code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 50; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="row"> <hr style="border-top: 3px solid #d71e1e;"><div style="height:183px; overflow:hidden;" class=" col-lg-6" ><label>Item Name</label><input type="text" id="myInput" name="item_name[]" onkeyup="myFunction()" class="form-control" placeholder="Enter Item Name" ><ul id="myUL" class="list-group" style="overflow:auto;height:125px;" ><?php $data = $this->inn->show_menu();foreach($data as $key=>$val){ if(!empty($val)){ ?><li class="list-group-item" ><?php echo $val->item_name; ?></li><?php } }?></ul></div><div class=" col-lg-6" ><label>Quantity</label><select class="form-control" name="quantity[]" required><option value="half">Half</option><option value="full">Full</option></select> </div> <br> Remove This Item </div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<div class="container-fluid">
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<h2 class="text-center">Creat Order</h2>
<hr>
<form class="form-group" action="<?php echo base_url('home/place_order'); ?>" method="post">
<div class="form-group col-lg-12">
<label >Food For</label>
<br>
<select class="form-control" name="for" required>
<option value="outside">Outside</option>
<option value="zomato">Zomato</option>
<option value="swiggy">Swiggy</option>
<?php
$rooms = $this->inn->show_room_no();
if (!empty($rooms))
{
foreach ($rooms as $rooms)
{
?>
<option value="<?php echo $rooms->room_no; ?>"><?php echo $rooms->room_no; ?></option>
<?php
}
}
else {
?>
<option >Choose Room Number if not available add in settings.</option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<div class="form-group col-lg-6">
<label>Item Name</label>
<input type="text" id="myInput" name="item_name[]" onkeyup="myFunction()" class="form-control" placeholder="Enter Item Name" >
<ul id="myUL" class="list-group" style="overflow:auto;height:125px;">
<?php
$data = $this->inn->show_menu();
foreach($data as $key=>$val)
{
if(!empty($val))
{
?>
<li class="list-group-item" id="listval" ><?php echo $val->item_name; ?></li>
<!--<li class="list-group-item" id="listval" ><?php // echo $val->item_name; ?></li>-->
<?php
}
}
?>
</ul>
</div>
<div class="form-group col-lg-6">
<label>Quantity</label>
<select class="form-control" name="quantity[]" required>
<option value="half">Half</option>
<option value="full">Full</option>
</select>
</div>
</div>
<div class="form-group input_fields_wrap col-lg-12">
<button class="add_field_button btn btn-primary">Add More Items</button>
<br><br>
</div>
<button type="submit" class="submit btn btn-success btn-block btn-lg">Place the Order</button>
</form>
</div>
</div>
</div>
<script>
var items = document.querySelectorAll("#myUL li");
for ( var i = 0; i < items.length; i++ )
{
items[i].onclick = function () {
document.getElementById("myInput").value = this.innerHTML;
};
}
</script>
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
Add key to everytime your append an element form like this :
From :
name="item_name[]"
To:
name="item_name[' + x + ']" //x is your key
I am studying the dbforge, and trying to apply it with my website. My basis or guide is the localhost/phpmyadmin where you will create a new table, i am done with the part of table name, name,type,attribute,length of the column and also the adding the column(see the picture below) .
Question: How can I retrieve all the post value?
Note: I tried to echo json_encode($_POST); im only getting 1 value.
View
<form id="new-table">
<div class="col-md-6">
<label>Table Name:</label>
<input type="hidden" name="type" value="new_table">
<input type="text" class="form-control border-input" name="table_name" id="table_name"><br>
<div class="text-danger" id="table_name_error"></div>
</div>
<!-- col-md-6 -->
<div class="col-md-3">
<label>Columns:</label>
<!-- <input type="text" class="form-control border-input" name="table_name" id="table_name"> -->
<input type="text" class="form-control border-input" id="number_of_column" >
</div>
<div class="col-md-3">
<br>
<button type="button" class="btn btn-info btn-fill btn-wd" onclick="addColumn()">Add</button>
</div>
<!-- col-md-3 -->
</div> <!-- row-->
<!-- <input type='button' value='Add Children' id='addButton' class="btn btn-sm btn-primary"> -->
<div class="row">
<div class="col-md-2">
<h6>Name</h6>
<input type="text" class="form-control border-input" name="field_name" id="field_name">
<div class="text-danger" id="field_name_error"></div>
</div>
<div class="col-md-2">
<h6>Type</h6>
<select class="form-control border-input" name="field_type" id="field_type">
<option value="volvo">Varchar</option>
<option value="saab">Int</option>
<option value="mercedes">Date</option>
<option value="audi">Text</option>
</select>
</div>
<div class="col-md-2">
<h6>Length/Value</h6>
<input type="text" class="form-control border-input" name="field_length" id="field_length">
<div class="text-danger" id="field_length_error"></div>
</div>
<div class="col-md-2">
<h6>Default</h6>
<input type="text" class="form-control border-input" name="field_default" id="field_default">
<div class="text-danger" id="field_default_error"></div>
</div>
<div class="col-md-2">
<h6>Attributes</h6>
<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">
<div class="text-danger" id="field_attributes_error"></div>
</div>
<div class="col-md-2">
<h6>Null</h6>
<input type="text" class="form-control border-input" name="field_null" value="null"><br>
<div class="text-danger" id="field_null_error"></div>
</div>
<div id="append">
<div id="TextBoxDiv1">
</div>
</div>
</div> <!-- row -->
<div class="text-right">
<button type="submit" class="btn btn-info btn-fill btn-wd">Update Profile</button>
</div>
</div>
<div class="clearfix"></div>
</form>
Controller
JS
My creating new column function
function addColumn()
{
var i = 0;
var columns = document.getElementById("number_of_column").value;
for(i=1;i<=columns;i++)
{
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' );
newTextBoxDiv.after().html('<div class="col-md-2">'+
'<label>Name</label>'+
'<input type="text" class="form-control border-input" name="field_name[]" id="field_name[]">'+
'<div class="text-danger" id="children_fname_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Type</h6>'+
'<select class="form-control border-input" name="field_type[]" id="field_type[]">'+
'<option value="volvo">Varchar</option>'+
'<option value="saab">Int</option>'+
'<option value="mercedes">Date</option>'+
'<option value="audi">Text</option>'+
'</select>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Length/Value</h6>'+
'<input type="text" class="form-control border-input" name="field_length[]" id="field_length[]">'+
'<div class="text-danger" id="field_length_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Default</h6>'+
'<input type="text" class="form-control border-input" name="field_default" id="field_default">'+
'<div class="text-danger" id="field_default_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Attributes</h6>'+
'<input type="text" class="form-control border-input" name="field_attributes" id="field_attributes">'+
'<div class="text-danger" id="field_attributes_error"></div>'+
'</div>'+
'<div class="col-md-2">'+
'<h6>Null</h6>'+
'<input type="text" class="form-control border-input" name="field_null" id="field_null"><br>'+
'<div class="text-danger" id="field_null_error"></div>'+
'</div>'
);
newTextBoxDiv.appendTo("#append");
}
document.getElementById("number_of_column").value = "";
}
** My submit form**
$(document).ready(function(){
$("#new-table").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-edit-content-1","Update Successfully!");
window.setTimeout(function(){location.href=base_url+"administrator/view_content"},2000);
}
else{
$("#table_name_error").html(result.table_name_error);
$("#field_name_error").html(result.field_name_error);
$("#field_type_error").html(result.field_type_error);
$("#field_length_error").html(result.field_length_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
In your code, I see you already have an input with name="field_name" and in the addColumn()
function you are also adding another input with the same name.
When you have a input named "field_name" in the form and later you again dynamically add another input with the same name again, they replaces one another and there is only one of their value present in the post data with that same name.
You can use array inputs here, like
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
<input name="field_name[]" ... />
<input name="field_type[]" ... />
...
You will get the Post array like:
Array
(
[field_name] => Array
(
[0] => fv1
[1] => fv2
....
)
[field_type] => Array
(
[0] => ftv1
[1] => ftv12
...
)
)
So for parsing:
$fields_array = array();
$no_of_fields = isset($_POST['field_name'])? count($_POST['field_name']) : 0;
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name'][$i])) $tmp[] = $_POST['field_name'][$i];
if (isset($_POST['field_type'][$i])) $tmp[] = $_POST['field_type'][$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
It is a little bit errorprone(assuming field_name, field_type will have arrays of same number of elements, if one is missing the parallel serial among them will be corrupted) approach.
Better to use counter for the fields.
For example:
<input name="no_of_fields" value="1"/>
Which's value will be increased in each addition.
And your form be like:
<input name="field_name_1" .../>
<input name="field_type_1" .../>
...
<input name="field_name_2" .../>
<input name="field_type_2" .../>
...
<input name="field_name_3" .../>
<input name="field_type_3" .../>
...
For parsing on the server side, you can go for:
$fields_array = array();
$no_of_fields = isset($_POST['no_of_fields'])? intval($no_of_fields) : 0;
if ($no_of_fields > 0) {
for ($i=1; $i<=$no_of_fields; $i++) {
$tmp = array();
if (isset($_POST['field_name_'.$i])) $tmp[] = $_POST['field_name_'.$i];
if (isset($_POST['field_type_'.$i])) $tmp[] = $_POST['field_type_'.$i];
...
if (!empty($tmp)) $fields_array[] = array();
}
}
// Now process/output the $fields_array;
If I put my code in a single file to get a single webpage I get the results.
When introduce to the main page via get data with a function type with ajax it's not working, tried multiple solution but no winning one.
I've put the script tag with the url for ckeditor and still no luck.
But if I code it like just one page for a single website page, ckeditor works fine but not when link to another coded page in 2 separate files.
Need help and thanks
I've tried CKEDITOR.replaceAll(); in the script at the bottom of page before the end body tag like suggested and still only works for the first textarea.
I'll put the 2 files in question
items_list.php
<?php
include "../includes/db.php";
if(isset($_POST['item_submit'])){
//mysqli_real_escape_string is a web protection for intrusion
$item_title = mysqli_real_escape_string($conn, strip_tags($_POST['item_title']));
$item_description = mysqli_real_escape_string($conn, $_POST['item_description']);
$item_category = mysqli_real_escape_string($conn, strip_tags($_POST['item_category']));
$item_qty = mysqli_real_escape_string($conn, strip_tags($_POST['item_qty']));
$item_cost = mysqli_real_escape_string($conn, strip_tags($_POST['item_cost']));
$item_price = mysqli_real_escape_string($conn, strip_tags($_POST['item_price']));
$item_discount = mysqli_real_escape_string($conn, strip_tags($_POST['item_discount']));
$item_delivery = mysqli_real_escape_string($conn, strip_tags($_POST['item_delivery']));
if(isset($_FILES['item_image']['name'])){
$file_name = $_FILES['item_image']['name'];
$path_address = "../images/items/$file_name";
$path_address_db = "images/items/$file_name";
$img_confirm = 1;
$file_type = pathinfo($_FILES['item_image']['name'], PATHINFO_EXTENSION);
if($_FILES['item_image']['size']>200000){
$img_confirm = 0;
echo "size 2 big";
}
if($file_type != 'jpg' && $file_type != 'png' && $file_type != 'gif'){
$img_confirm = 0;
echo "type mismatch";
}
if($img_confirm == 0){
}else{
if(move_uploaded_file($_FILES['item_image']['tmp_name'], $path_address)){
$item_ins_sql = "INSERT INTO items (item_image, item_title, item_description, item_cat, item_qty, item_cost, item_price, item_discount, item_delivery) VALUES ('$path_address_db','$item_title','$item_description','$item_category','$item_qty','$item_cost','$item_price','$item_discount','$item_delivery')";
$item_ins_run = mysqli_query($conn, $item_ins_sql);
}
}
}else{
echo "sorry";
}
}
if( isset($_POST['edit_submit'])){
//include "item_list_process.php";
$item_id = mysqli_real_escape_string($conn, strip_tags($_POST['item_id']));
$item_title = mysqli_real_escape_string($conn, strip_tags($_POST['item_title1']));
$item_description = mysqli_real_escape_string($conn, $_POST['item_description1']);
$item_category = mysqli_real_escape_string($conn, strip_tags($_POST['item_cat']));
$item_qty = mysqli_real_escape_string($conn, strip_tags($_POST['item_qty']));
$item_cost = mysqli_real_escape_string($conn, strip_tags($_POST['item_cost']));
$item_price = mysqli_real_escape_string($conn, strip_tags($_POST['item_price']));
$item_discount = mysqli_real_escape_string($conn, strip_tags($_POST['item_discount']));
$item_delivery = mysqli_real_escape_string($conn, strip_tags($_POST['item_delivery']));
echo $item_id;
$item_up_sql = "UPDATE items SET item_title = '$item_title', item_description = '$item_description', item_cat = '$item_category', item_qty = '$item_qty', item_cost = '$item_cost', item_price = '$item_price', item_discount = '$item_discount', item_delivery = '$item_delivery' WHERE item_id = '$item_id' ";
$item_up_run = mysqli_query($conn, $item_up_sql);
}
?>
<html>
<head>
<title>Online Shopping | Admin Panel</title>
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/admin_style.css">
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap.js"></script>
<script src="https://cdn.ckeditor.com/4.7.1/standard-all/ckeditor.js"></script>
<script>
function get_item_list_data(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('get_item_list_data').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'item_list_process.php', true);
xmlhttp.send();
}
function del_item(item_id){
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('get_item_list_data').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'item_list_process.php?del_item_id='+item_id, true);
xmlhttp.send();
}
</script>
</head>
<body onload="get_item_list_data()">
<?php include "includes/header.php"; ?>
<div class="container">
<button class="btn btn_red btn-danger" data-toggle="modal" data-target="#add_new_item" data-backdrop="static" data-keyboard="false">Add New Item</button>
<div id="add_new_item" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Item</h4>
</div>
<div class="modal-body">
<form method="post" enctype="multipart/form-data" name="addNewItemForm">
<div class="form-group">
<label>Item Image</label>
<input type="file" id="image" name="item_image" class="form-control" placeholder="Enter location on drive for the image of item" required>
</div>
<div class="form-group">
<label>Item Title</label>
<input type="text" id="item_title" name="item_title" class="form-control" placeholder="Enter Title or Name of Item" required>
</div>
<div class="form-group">
<label>Item Description</label>
<!------Here is the ckeditor that's working-------------->
<textarea class="form-control ckeditor" id="item_description" name="item_description" required></textarea>
</div>
<div class="form-group">
<label>Item Category</label>
<select class="form-control" name="item_category" required>
<option>Select a Category</option>
<?php
$cat_sql = "SELECT * FROM item_cat";
$cat_run = mysqli_query($conn, $cat_sql);
while($cat_rows = mysqli_fetch_assoc($cat_run)){
$cat_name = ucwords($cat_rows['cat_name']);
if($cat_rows['cat_slug'] == ''){
$cat_slug = $cat_rows['cat_name'];
}else{
$cat_slug = $cat_rows['cat_slug'];
}
echo "
<option value='$cat_slug'>$cat_name</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Item Quantity</label>
<input type="number" name="item_qty" class="form-control" placeholder="Enter the quantity you have in stocks" required>
</div>
<div class="form-group">
<label>Item Cost</label>
<input type="number" name="item_cost" class="form-control" placeholder="Enter the cost you paid for the item" required>
</div>
<div class="form-group">
<label>Item Price</label>
<input type="number" name="item_price" class="form-control" placeholder="Enter the price to sell to clients" required>
</div>
<div class="form-group">
<label>Item Discount</label>
<input type="number" name="item_discount" class="form-control" placeholder="Enter the amount of discount in dollars we are giving" >
</div>
<div class="form-group">
<label>Item Delivery</label>
<input type="number" name="item_delivery" class="form-control" placeholder="Enter the amount to charge for shipping">
</div>
<div class="form-group">
<input type="submit" name="item_submit" class="btn btn-primary btn-block" value="SUBMIT">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn_red btn-danger" data-dismiss="modal">CLOSE</button>
</div>
</div>
</div>
</div>
<div id="get_item_list_data">
<!---------------------Area for process item list data------------>
</div>
</div>
<?php include "includes/footer.php"; ?>
<script>
//CKEDITOR.replaceAll();
// CKEDITOR.instances.item_description.destroy();
//CKEDITOR.replace( 'item_description' );
//ckeditorOff();
//CKEDITOR.add
//CKEDITOR.replace( 'item_description1' );
</script>
</body>
</html>
Second file item_list_process.php
<?php
include "../includes/db.php";
if(isset($_REQUEST['del_item_id'])){
$del_sql = "DELETE FROM items WHERE item_id = '$_REQUEST[del_item_id]'";
$del_run = mysqli_query($conn, $del_sql);
}
?>
<table class="table table-bordered table-striped">
<thead>
<tr class="item-head">
<th>S. no.</th>
<th>Image</th>
<th>Item Title</th>
<th>Item Description</th>
<th>Item Category</th>
<th>Item Qty</th>
<th>Item Cost</th>
<th>Item Price</th>
<th>Item Discount</th>
<th>Item Delivery</th>
</tr>
</thead>
<tbody>
<?php
$c = 1;
$sel_sql = "SELECT * FROM items";
$sel_run = mysqli_query($conn, $sel_sql);
while($rows = mysqli_fetch_assoc($sel_run)){
$discountPrice = $rows['item_price'] - $rows['item_discount'];
echo "
<tr>
<td>$c</td>
<td><img src='../$rows[item_image]' style='width:30px'></td>
<td>$rows[item_title]</td>
<td>"; echo strip_tags($rows['item_description']); echo "</td>
<td>$rows[item_cat]</td>
<td>$rows[item_qty]</td>
<td>$rows[item_cost]</td>
<td>$rows[item_price]</td>
<td>$discountPrice($rows[item_discount])</td>
<td>
<div class='dropdown'>
<button class='btn btn_red btn-danger dropdown-toggle' data-toggle='dropdown'>Actions<span class='caret'></span></button>
<ul class='dropdown-menu dropdown-menu-right'>
<li>
<a href='#edit_modal$rows[item_id]' data-toggle='modal' >Edit</a>
</li>";
?>
<li>Delete</li>
<?php
echo "
</ul>
</div>
<div class='modal fade ' id='edit_modal$rows[item_id]' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'>Edit Item</h4>
</div>
<div class='modal-body'>
<form method='post' name='editForm'>
<input type='hidden' name='item_id' id='item_id' value='$rows[item_id]'>
<div class='form-group'>
<label>Item Title</label>
<input type='text' value='$rows[item_title]' id='item_title1' name='item_title1' class='form-control' required>
</div>
<div class='form-group' id='tracking_text'>
<label>Item Description</label>
//-------------------This is for the second ckeditor--------------- >
<textarea class='form-control ckeditor' name='item_description1' id='item_description11' required>$rows[item_description]</textarea>
</div>
<div class='form-group'>
<label>Item Category</label>
<select class='form-control' value='$rows[item_cat]' name='item_cat' id='item_cat' required>
";
$cat_sql = "SELECT * FROM item_cat";
$cat_run = mysqli_query($conn, $cat_sql);
while($cat_rows = mysqli_fetch_assoc($cat_run)){
$cat_name = ucwords($cat_rows['cat_name']);
if($cat_rows['cat_slug'] == ''){
$cat_slug = $cat_rows['cat_name'];
}else{
$cat_slug = $cat_rows['cat_slug'];
}
if($cat_slug == $rows['item_cat']){
echo "
<option selected value='$cat_slug'>$cat_name</option>";
}else{
echo "
<option value='$cat_slug'>$cat_name</option>";
}
}
echo "
</select>
</div>
<div class='form-group'>
<label>Item Quantity</label>
<input type='number' value='$rows[item_qty]' name='item_qty' id='item_qty' class='form-control' required>
</div>
<div class='form-group'>
<label>Item Cost</label>
<input type='number' value='$rows[item_cost]' name='item_cost' id='item_cost' class='form-control' required>
</div>
<div class='form-group'>
<label>Item Price</label>
<input type='number' value='$rows[item_price]' name='item_price' id='item_price' class='form-control' required>
</div>
<div class='form-group'>
<label>Item Discount</label>
<input type='number' value='$rows[item_discount]' name='item_discount' id='item_discount' class='form-control'>
</div>
<div class='form-group'>
<label>Item Delivery</label>
<input type='number' value='$rows[item_delivery]' name='item_delivery' id='item_delivery' class='form-control'>
</div>
<div class='form-group'>
";
?>
<button type="submit" name="edit_submit" id="edit_submit" class='btn btn-primary btn-block' >SUBMIT</button>
</div>
</form>
</div> <!---end of modal body--->
<div class='modal-footer'>
<button class='btn btn_red btn-danger' data-dismiss='modal'>CLOSE</button>
</div>
</div> <!---end of modal content--->
</div> <!---end of modal dialog--->
</div> <!---end of modal div fade--->
</td>
</tr>
<?php
$c++;
}
?>
</tbody>
</table>
This is my whole code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pre-Enrollment</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/customcss.css">
</head>
<nav>
<ul class="nav nav-tabs">
<li role="presentatoion" class="active">Pre-Enrollment</li>
<li role="presentation">Students</li>
<li role="presentation">Subjects</li>
</ul>
</nav>
<br>
<body>
<div class="container">
<div class="row"> <!--RED-->
<div class="col-md-3" >
<form id="idNumber" action="FromEnrollment.php" method="POST">
<div class="input-group">
<!-- <input type="text" class="form-control" placeholder="ID NUMBER"> -->
<span class="input-group-btn">
<!--<form action="newPhp.php" method="POST">-->
<input type="text" placeholder="ID NUMBER" class="form-control" name="input">
<input type="submit" value="Enter" name"Enter" class="btn btn-default">
<!--</form>-->
<button class="btn btn-default" type="button" onclick="resetIdNumber()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-4 col-md-offset-3">
<select style="width: 120px;">
<option value="All">Overall Term</option>
<option value="First">First Term</option>
<option value="Second">Second Term</option>
<option value="Short">Short Term</option>
</select>
</div>
<div class="col-md-2">
<button class="btn btn-primary" type="button">Apply</button>
<button class="btn btn-default" type="button" onclick="myFunction()" value="reset">Reset</button>
</div>
</div>
<br>
<div class="row" >
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if( isset($_POST['input']) ){
include 'dbcon.php';
$Idnumber = ($_POST['input']);
$stmt = $pdo->query("SELECT * FROM students WHERE id_number = '$Idnumber'");
$currentTerm = $pdo->query("SELECT * FROM pre_enroll WHERE id_number = '$Idnumber'");
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result2 = $currentTerm->fetchAll(PDO::FETCH_ASSOC);
// $last_name = print_r($result[0]['last_name']);
// $first_name = print_r($result[0]['first_name']);
// $course = print_r($result[0]['course']);
echo "
<div class='col-md-2'>
<p>Name: ";
print_r($result[0]['last_name']);
echo " ";
print_r($result[0]['first_name']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Course and Year: ";
print_r($result[0]['course']);
echo"-";
print_r($result[0]['year']);
echo"</p>
</div>";
echo "
<div class='col-md-4'>
<p>Current term: ";
print_r($result2[0]['term']);
echo"</p>
</div>";
// <div class='col-md-4'>
// <p>Current Term: </p>
// </div>;
}
}else{
echo "
<div class='col-md-2'>
<p>Name: </p>
</div>
<div class='col-md-4'>
<p>Course and Year: </p>
</div>
<div class='col-md-4'>
<p>Current Term: </p>
</div>";
}
?>
</div>
<br>
<div class="row">
<div class="col-md-6">
<form id="Subjects" action="#">
<div class="input-group">
<input type="text" id="myInput" onkeyup="filterData()" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="resetSubjects()" value="reset">Reset</button>
</span>
</div>
</form>
</div>
<div class="col-md-2">
<p>Total Units: <b> </b></p>
</div>
</div>
<br>
<?php
include 'dbcon.php';
$stmt = $pdo->query("SELECT subjects.coursenumber as 'Course No.', subjects.destitle as 'Descriptive Title', enr_stat.term as 'Term', subjects.units as 'Units' FROM subjects INNER JOIN enr_stat ON subjects.coursenumber = enr_stat.coursenumber");
?>
<div class="row">
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="myTable">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
<?php
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
// echo "<form action=''>";
echo "<tr>";
echo "<td>".$row['Course No.']."</td>";
echo "<td>".$row['Descriptive Title']."</td>";
echo "<td>".$row['Term']."</td>";
echo "<td>".$row['Units']."</td>";
echo "<input type='hidden' name='CourseNo' value='".$row['Course No.']."'/>";
echo "<input type='hidden' name='descrp' value='".$row['Descriptive Title']."'/>";
echo "<input type='hidden' name='term' value='".$row['Term']."'/>";
echo "<input type='hidden' name='units' value='".$row['Units']."'/>";
echo "
<td>
<button class='btn btn-default btn-sm' onclick='addDataToLocalStorage(this)'>
<span class='glyphicon glyphicon-plus' aria-hidden='true'></span>
</button>
</td>
";
echo "</tr>";
// echo "</form>";
}
?>
</table>
</div>
</div>
<div class="col-md-6 col" id="table-wrapper">
<div id="table-scroll">
<table class="table" id="copy">
<tr>
<th>Course No.</th>
<th>Descriptive Title</th>
<th>Term</th>
<th>Unit</th>
<th></th>
</tr>
</table>
</div>
</div>
</div>
<div class="col-md-offset-11">
<button class="btn btn-primary" type="button">Apply</button>
<br>
</div>
<script>
function resetIdNumber(){
document.getElementById("idNumber").reset();
}
function resetSubjects(){
document.getElementById("Subjects").reset();
}
function filterData() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function addDataToLocalStorage(r){
var courseNo = r.parentNode.parentNode.childNodes[0].innerText;
var descriptive = r.parentNode.parentNode.childNodes[1].innerText;
var term = r.parentNode.parentNode.childNodes[2].innerText;
var unit = r.parentNode.parentNode.childNodes[3].innerText;
var t = "<button onclick=clearData(this);deleteRow(this); class='btn btn-default btn-sm'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
// alert(courseNo + " " + descriptive + " " + unit);
var list = {
courseNumber: courseNo,
descriptiveTitle: descriptive,
term: term,
units: unit,
};
var jsonObject = JSON.stringify(list);
localStorage.setItem("list" + localStorage.length,jsonObject);
var thatTable = document.getElementById("copy");
var newRow = thatTable.insertRow(-1); //at the last position of the table
var newCell1 = newRow.insertCell(0);
newCell1.innerHTML = courseNo;
var newCell2 = newRow.insertCell(-1);
newCell2.innerHTML = descriptive;
var newCell3 = newRow.insertCell(-1);
newCell3.innerHTML = term;
var newCell4 = newRow.insertCell(-1);
newCell4.innerHTML = unit;
var newCell5 = newRow.insertCell(-1);
newCell5.innerHTML = t;
}
function clearData(r) {
var data = r.parentNode.parentNode.rowIndex;
var data_key = data - 1;
localStorage.removeItem(localStorage.key(data_key));
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("copy").deleteRow(i);
}
// function refresh(){
// if (localStorage.getItem("list0") != null) { ///if there is "student1" exist in localStorage
// for(i = 0; i <= localStorage.length; i++){
// var stores = localStorage.getItem("list" + i);
// var jsonString = JSON.parse(stores); //convert text to javascript object
// var thatTable = document.getElementById("copy");
// var newRow = thatTable.insertRow(-1); //at the last position of the table
// var newCell1 = newRow.insertCell(0);
// newCell1.innerHTML = courseNo;
// var newCell2 = newRow.insertCell(-1);
// newCell2.innerHTML = descriptive;
// var newCell3 = newRow.insertCell(-1);
// newCell3.innerHTML = term;
// var newCell4 = newRow.insertCell(-1);
// newCell4.innerHTML = unit;
// var newCell5 = newRow.insertCell(-1);
// newCell5.innerHTML = t;
// }
// }
//}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
How can I increment my <p>Total Units:<b> </b></p> whenever I clicked add button in my table. My table fetched some data in my database and when I clicked add, The data will copy in the next html table. I want every time I clicked the add button, my <p> tag will increment by how many units the subject is.
I tried using the stepUp() method in js but I dont know how to get the value of the units row in my html table. Is there any way to do it with my current codes?
You can just use a span with special ID
<p>Total Units:<b><span id="countRow"></span></b></p>
Then count your rows, and just
document.getElementById("countRow").innerHTML = count
Set any class name to the column units like this
<td class="unit" >2</td>
Each time of button click after run the each function like this
var total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
And set any class name to p tag
$('.p_tag_class').html('Total Units:' +total+'<b> </b>');
Update 1:
$(document).on('click','[type="button"]',function(){
$('table tbody').last('tr').append('<tr><td >2</td><td class="unit">8</td></tr>');
total=0;
$('.unit').each(function(){ total+=parseInt($(this).text()); });
$('.total').text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1px">
<thead>
<tr>
<th>colum1</th>
<th >colum2</th>
</tr>
</thead>
<tbody>
<tr>
<td >1</td>
<td class="unit">6</td>
</tr>
<tr>
<td >2</td>
<td class="unit">8</td>
</tr>
</tbody>
</table>
<input type="button" value="new row" />
<p class="total" ></p>
New Code(not working) :
(index.php) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Workorder System</title>
<!-- Bootstrap core CSS -->
<link href="css/jquery-ui.min.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/sticky-footer-navbar.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Begin page content -->
<div class="container content">
<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<h1 class="text-center title">Workorder System </h1>
</div>
<h2> </h2>
<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
<th width="15%">Model #</th>
<th width="38%">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off"></td>
<td>
<input type="text" data-type="model" name="modelName[]" id="modelName_1" class="form-control autocomplete_txt" autocomplete="off">
</td>
<td>
<input type="text" data-type="category" name="category[]" id="categoryName_1" class="form-control autocomplete_txt" autocomplete="off">
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class='row'>
<div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
<button class="btn btn-danger delete" type="button">- Delete</button>
<button class="btn btn-success addmore" type="button">+ Add More</button>
</div>
<div class='col-xs-12 col-sm-offset-4 col-md-offset-4 col-lg-offset-4 col-sm-5 col-md-5 col-lg-5'>
<form class="form-inline">
<div class="form-group">
<label>Subtotal: </label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="number" class="form-control" id="subTotal" placeholder="Subtotal" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax: </label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="number" class="form-control" id="tax" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Tax Amount: </label>
<div class="input-group">
<input type="number" class="form-control" id="taxAmount" placeholder="Tax" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
<div class="input-group-addon">%</div>
</div>
</div>
<div class="form-group">
<label>Total: </label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="number" class="form-control" id="totalAftertax" placeholder="Total" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Amount Paid: </label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="number" class="form-control" id="amountPaid" placeholder="Amount Paid" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
<div class="form-group">
<label>Amount Due: </label>
<div class="input-group">
<div class="input-group-addon">$</div>
<input type="number" class="form-control amountDue" id="amountDue" placeholder="Amount Due" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;">
</div>
</div>
</form>
</div>
</div>
<h2>Notes: </h2>
<div class='row'>
<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
<div class="form-group">
<textarea class="form-control" rows='5' id="notes" placeholder="Your Notes"></textarea>
</div>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<script src="js/auto.js"></script>
</body>
</html>
(auto.js) :
//adds extra table rows
var i=$('table tr').length;
$(".addmore").on('click',function(){
html = '<tr>';
html += '<td><input class="case" type="checkbox"/></td>';
html += '<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="model" name="modelName[]" id="modelName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '<td><input type="text" data-type="category" name="category[]" id="categoryName_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
//to check all checkboxes
$(document).on('change','#check_all',function(){
$('input[class=case]:checkbox').prop("checked", $(this).is(':checked'));
});
//deletes the selected table rows
$(".delete").on('click', function() {
$('.case:checkbox:checked').parents("tr").remove();
$('#check_all').prop("checked", false);
calculateTotal();
});
//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
if(type =='productCode' )autoTypeNo=0;
if(type =='model' )autoTypeNo=1;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[autoTypeNo],
value: code[autoTypeNo],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#itemNo_'+id[1]).val(names[0]);
$('#modelName_'+id[1]).val(names[1]);
$('#cateogryName_'+id[1]).val(names[1]);
calculateTotal();
}
});
});
//price change
$(document).on('change keyup blur','.changesNo',function(){
id_arr = $(this).attr('id');
id = id_arr.split("_");
quantity = $('#quantity_'+id[1]).val();
price = $('#price_'+id[1]).val();
if( quantity!='' && price !='' ) $('#total_'+id[1]).val( (parseFloat(price)*parseFloat(quantity)).toFixed(2) );
calculateTotal();
});
$(document).on('change keyup blur','#tax',function(){
calculateTotal();
});
//total price calculation
function calculateTotal(){
subTotal = 0 ; total = 0;
$('.totalLinePrice').each(function(){
if($(this).val() != '' )subTotal += parseFloat( $(this).val() );
});
$('#subTotal').val( subTotal.toFixed(2) );
tax = $('#tax').val();
if(tax != '' && typeof(tax) != "undefined" ){
taxAmount = subTotal * ( parseFloat(tax) /100 );
$('#taxAmount').val(taxAmount.toFixed(2));
total = subTotal + taxAmount;
}else{
$('#taxAmount').val(0);
total = subTotal;
}
$('#totalAftertax').val( total.toFixed(2) );
calculateAmountDue();
}
$(document).on('change keyup blur','#amountPaid',function(){
calculateAmountDue();
});
//due amount calculation
function calculateAmountDue(){
amountPaid = $('#amountPaid').val();
total = $('#totalAftertax').val();
if(amountPaid != '' && typeof(amountPaid) != "undefined" ){
amountDue = parseFloat(total) - parseFloat( amountPaid );
$('.amountDue').val( amountDue.toFixed(2) );
}else{
total = parseFloat(total).toFixed(2);
$('.amountDue').val( total );
}
}
//It restrict the non-numbers
var specialKeys = new Array();
specialKeys.push(8,46); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode;
console.log( keyCode );
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
return ret;
}
//datepicker
$(function () {
$('#invoiceDate').datepicker({});
});
(ajax.php)
<?php
require_once 'config.php';
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$query = "SELECT model, category FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['model'].'|'.$row['category'];>>
array_push($data, $name);
}
echo json_encode($data);exit;
}
This is a sample of what I am trying to get to function. When you click in the "Model #" field, it should auto correct from a "products" database with the needed data. Right now it has "model,category" but the end result should have :
model, category, subcategory, description, cost, retail
I cannot for the life of me figure out how to fix this to where it autocompletes correctly :(
in the first code there are two required vars, the name and type with which the query is made in the database to return the information, as I see in the second code not you are considering .. before creating the query.. also you could check console log with dev tools on your browser to get error
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
} else { return false; }
$query = "SELECT ID, model, category, subcategory, description, cost, retail FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
....
the type var is the data-type in input type element using in js and send it as aditional post var .. check here:
html += '<td><input type="text" data-type="productCode" name="itemNo[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off"></td>';
and here
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
the type and name vars are send here in the ajax call
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
and those vars are "captured" using php $_POST you see.. in the ajax call the data option make 2 vars name_startsWith, type and in the php code $type = $_POST['type']; $name = $_POST['name_startsWith'];