I have a form on my website where users fill an input field and selects from a drop down. For more options, a button is provided to generate more fields dynamically for users. That works fine.
Now, I’m trying to implement a functionality that previews the orders made by users (in a table format) immediately the user finish filling the orders field and the name field receives focus but I can’t seems to get it done. Any assistance will be appreciated please.
Here is what I’ve tried so far:
<form class="form-horizontal" method="post" action="" id="order_form">
<fieldset class="orders_det">
<div class="form-group">
<label for="prod_type">Type</label>
<select name="prod_type[]" class="form-control prod">
<option value="">-- Select Products --</option>
<option value="prod1">Prod1</option>
<option value="prod2">Prod2</option>
<option value="prod3">Prod3</option>
</select>
</div>
<div class="form-group">
<label for="quant" >
<input type="text" class="form-control quant" name="quant[]">
</label>
<div>
<button type="button" class="btn btn-success" id="more_btn">Add More Orders + </button>
</div>
</fieldset>
<div class="form-group">
<label for="name" class="col-md-2 control-label">Name</label>
<div class="col-md-8">
<input type="text" class="form-control name" name="name">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" name="order_submit" id="order_submit">Submit Order</button>
</div>
</form>
<div class="orders_preview"></div>
My jquery:
$("form input.name").on("focus", function(e){
var prod = $("form select[name='prod_type[]']").map(function(){
return $(this).val();
}).get();
var quant = $("form input[name='quant[]']").map(function(){
return ($(this).val());
}).get();
var table = '';
table = '<table>';
table = '<thead>';
table = '<tr>';
table = '<th>Product</th>';
table = '<th>Quantity</th>';
table = '</tr>';
table = '</thead>';
table = '<tbody>';
table = '<tr>';
table = '<td>'+prod+'</td>';
table = '<td>'+quant+'</td>';
table = '</tr>';
table = '</tbody>';
table = '</table>';
$(".orders_preview").append(table);
});
I will modify your jquery slightly, changing the event handler to 'on change' instead of 'on focus'. Also, just before the opening tr tag, i will loop through your var prod values, like so;
$("form").on("change", function(e) { //to generate a preview table
var prod = $("form select[name='prod_type[]']")
var quant = $("form input[name='quant[]']")
var table = '';
table += '<table>';
table += '<thead>';
table += '<tr>';
table += '<th>Product</th>';
table += '<th>Quantity</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
prod.each(function(i) {
table += '<tr>';
table += '<td>' + $(this).val() + '</td>';
table += '<td>' + quant.eq(i).val() + '</td>';
table += '</tr>';
})
table += '</tbody>';
table += '</table>';
$(".orders_preview").html(table);
});
You need to use += (concatenate each data to the variable)like below:-
table += '<table>';
table += '<thead>';...... so on for others
Working example:-
$(document).ready(function() {
$('form button#more_btn').on("click", function(e) {//to generate dynamic fields
e.preventDefault();
var moreOrders = '';
moreOrders += '<div class="new_order">';
moreOrders += '<div class="form-group">';
moreOrders += '<label for="prod_type">Type</label>';
moreOrders += '<select name="prod_type[]" class="form-control prod">';
moreOrders += '<option value="">-- Select Products --</option>';
moreOrders += '<option value="prod1">Prod1</option>';
moreOrders += '<option value="prod2">Prod2</option>';
moreOrders += '<option value="prod3">Prod3</option>';
moreOrders += '</select>';
moreOrders += '</div> ';
moreOrders += '<div class="form-group">';
moreOrders += '<label for="quant" class="control-label col-md-2" >Quantity</label>';
moreOrders += '<div class="form-control col-md-6">';
moreOrders += '<input type="text" class="form-control quant" name="quant[]">';
moreOrders += '</div>';
moreOrders += '<div>';
moreOrders += '</div><br />';
$('.more_orders').append(moreOrders);
});
$("form input.name").on("focus", function(e) {//to generate a preview table
var prododuct = $("form select[name='prod_type[]']");
var quantity = $("form input[name='quant[]']");
var table = '';
table += '<table>';
table += '<thead>';
table += '<tr>';
table += '<th>Product</th>';
table += '<th>Quantity</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
table += '<tr>';
prododuct.each(function(i) {
table += '<tr>';
table += '<td>' + $(this).val() + '</td>';
table += '<td>' + quantity.eq(i).val() + '</td>';
table += '</tr>';
})
table += '</tr>';
table += '</tbody>';
table += '</table>';
$(".orders_preview").append(table);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" method="post" action="" id="order_form">
<fieldset class="orders_det">
<div class="form-group">
<label for="prod_type">Type</label>
<select name="prod_type[]" class="form-control prod">
<option value="">-- Select Products --</option>
<option value="prod1">Prod1</option>
<option value="prod2">Prod2</option>
<option value="prod3">Prod3</option>
</select>
</div>
<div class="form-group">
<label for="quant" class="control-label col-md-2" >Quantity</label>
<div class="form-control col-md-6">
<input type="text" class="form-control quant" name="quant[]">
</div>
<div>
<button type="button" class="btn btn-success" id="more_btn">Add More Orders + </button>
</div>
</div>
<div class="more_orders">
</div>
</fieldset>
<div class="form-group">
<label for="name" class="col-md-2 control-label">Name</label>
<div class="col-md-8">
<input type="text" class="form-control name" name="name">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" name="order_submit" id="order_submit">Submit Order</button>
</div>
</form>
<div class="orders_preview"></div>
jsFiddle working link:- https://jsfiddle.net/8jmz4w14/
By itself = does not concatenate, so you need to use += to realize the full table:
var table = '';
table += '<table>';
table += '<thead>';
table += '<tr>';
table += '<th>Product</th>';
table += '<th>Quantity</th>';
table += '</tr>';
table += '</thead>';
table += '<tbody>';
table += '<tr>';
table += '<td>'+prod+'</td>';
table += '<td>'+quant+'</td>';
table += '</tr>';
table += '</tbody>';
table += '</table>';
Related
I have a table in which there is a row. The first cell of the row contains a drop-down list, and other rows are generated dynamically in case of an argument. The drop-down list contains an option with two fields from the database, one of which is text and the other is a number. The two are linked to each other. The problem that I am stuck with is that in the table The text and its associated number from the database appear only in the first row in the table, I want to repeat this in the table in the rest of the dynamically generated rows, that each text and its associated value appear in the drop down list
The problem in the image
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
$('.select_acount').on('change', function() {
$(this).closest('tr').find('.mount').val($(this).val());
});
var data = <?php echo json_encode($data); ?>;
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount"required></td><td class="td2"><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash" ></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
I have a table that contains a row with the ability to generate other dynamic rows. The drop-down list works now in every new row that is created. I have the first row. The drop-down list that carries data from the database works well and the data is shown in it well, but when adding a new dynamic row and when Clicking on the drop down list the values written on it all show with the word Undefined all the values of the drop down list written on it show up with the word : Undefined I am really stuck any suggestions would be appreciated and thanks
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`
I can not figure out how to get $output working within this function.
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
function fill_unit_select_box($conn)
{
$output = '';
$query = "SELECT * from `skater` ORDER By `skater`.`skater_name_first` ASC";
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["skater_NUM"].'">'.$row["skater_NUM"].''.$row["skater_NUM"].'</option>';
//$output .= '<option value="'.$row["skater_NUM"].'">'.$row["skater_name_first"].''.$row["skater_name_last"].'</option>';
}
return $output;
}
?>
Function is called later.
<option value="">Select Unit</option><?php echo fill_unit_select_box($conn); ?></select>
If I use the following nothing works. The option fields are not displayed in the select.
output .= '<option value="'.$row["skater_NUM"].'">'.$row["skater_name_last"].''.$row["skater_name_first"].'</option>';
If I use the following the function works.
output .= '<option value="'.$row["skater_NUM"].'">'.$row["skater_NUM"].''.$row["skater_NUM"].'</option>';
Calling anything except skater_NUM causes issues.
If I call the function outside of the following the function works.
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($conn); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
The function is working. Just the add row .add button will not add new rows with anything other then numbers for skater_NUM field.
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><option value="8">Skater1</option><option value="21">Skater2</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
the variable $output is replaced in every loop, $output will give you the result of the last row.
Solution try to replace $output by
$output .=
I figured it out... add ".." Now the echo likes characters other then numbers.... This took was too long.
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($conn); ?></select></td>';
to
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option>"<?php echo fill_unit_select_box($conn); ?>"</select></td>';
I am created form to select value to display in my page table.Below is my code to select multiple values and search to display, but it is not displaying the selected values (type and dates) in multiple dropdownlist. Anyone can help me solve this problem? Thanks.
My frontend coding:
<div class="box inverse">
<div class="row">
<div class="col-lg-12">
<header>
<h5>Search</h5>
</header>
<form id="transaction_search">
<div class="form-group">
<div class="col-lg-12">
<div class="col-lg-3">
</div>
<div class="col-lg-12">
<div class="form-group">
<div class="col-lg-12">
<label for="text1" class="form-group control-label col-lg-2"><?php echo $language['type']; ?>:</label>
<div class="col-lg-5">
<select id="select_type" class="form-group form-control required"">
<option value="transfer" selected><?php echo $language["transfer"]; ?></option>
<option value="withdraw"><?php echo $language["withdraw"]; ?></option>
<option value="upgrade"><?php echo $language["upgrade"]; ?></option>
<option value="register"><?php echo $language["register"]; ?></option>
<option value="receive"><?php echo $language["receive"]; ?></option>
</select>
</div>
</div>
</div>
<div class="col-lg-12 form-group">
<label for="text1" class="form-group control-label col-lg-2">Date Range:</label>
<div class="col-lg-2">
<?php echo custom_period_opt(); ?>
</div>
<label for="text1" class="form-group control-label col-lg-2">Date Created:</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="start_date" name="start_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
<label for="text1" class="form-group control-label col-lg-2">To</label>
<div class="col-lg-2">
<input type="text" class="form-group form-control datepicker" id="end_date" name="end_date" data-date-format="dd-mm-yyyy" title="" value="<?php echo $new_cur_date; ?>" readonly>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-12" style="text-align:center; padding-bottom:10px; padding-top:10px;">
<button id="search" type="button" class="btn btn-sm btn-primary" onclick="search_('transaction_search','transaction_result','transaction_table')">Search</button>
<button id="clear" type="button" class="btn btn-sm btn-default" onclick="clearData()">Clear</button>
</div>
<div class="body" id="transaction_result" style="overflow:auto;">
</div><!--body-->
</form>
</div>
</div>
My backend coding (This is part of coding I try to select "Withdraw" option to test output, but did't display any data in the table. This coding is want to select "withdraw" and select what I choose the "date"):
<?php
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
$select_type = $_POST['select_type'];
unset($arr_val['loc']);
unset($arr_val['action']);
unset($arr_val['select_type']);
$tbl_name = 'withdrawal_record';
if ($action == 'search' && $select_type == 'withdraw' ) {
if ($_POST['select_type'] != '' || $_POST['start_date'] != '' || $_POST['end_date'] != '' ) {
$sql = 'SELECT * FROM ' . $tbl_name . ' WHERE id is not null';
if($_POST['start_date']!='' && $_POST['end_date']!= '') {
$sql .=' and a.created between "' . date('Y-m-d', strtotime($_POST['start_date'])) . '" and "' . date('Y-m-d', strtotime($_POST['end_date'])) . '"';
}
$result_arr['sql'] = $sql;
$result_arr = get_data_list($sql);
$i = 1;
echo '<table id="dataTable_1" class="dataTable table table-bordered table-condensed table-hover table-striped" style="padding:0px;" border="1">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>';
foreach ($result_arr as $rs_search) {
echo "<tr>";
echo "<td>" . $i++ . "</td>";
echo "<td>" . $rs_search['created'] . "</td>";
echo "<td>" . $rs_search['withdraw_amount'] . "</td>";
echo '</td>';
echo "</tr>";
}
echo '</tbody>';
echo '</table>';
}
}
?>
Below is jquery function:
function search_(form_id, div_id, act_file) {
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
$.ajax({
//dataType: 'json',
type: 'POST',
url: '?f=' + act_file,
data: form_data,
beforeSend: function() {
show_overLay();
$('#' + div_id).html('');
},
success: function(data) {
hide_overLay('');
if (data) {
$("#" + div_id).append(data);
$('.dataTable').dataTable({
pageLength: 25,
destroy: true
});
} else {
hide_overLay("Please fill in the field.");
}
//console.log(data);
}
});
}
Below is my "withdrawal_record" table:
withdrawal_record
Below is my output, and didn't show the data what I select. Actually I want to select date between 04/11/19 and 07/11/19 and select type is "Withdraw" :
Output 1
If success , that will show like below the output picture:
Output 2
Error output:
Output 3
In html add multiple attribute to select :
<select id="select_type" class="form-group form-control required" multiple>
In JQuery make these changes:
Remove these :
var action = 'search';
var extra = '&action=' + action;
var serialized = $('#' + form_id).serialize();
var form_data = serialized + extra;
And in Ajax request:
Remove these lines:
data: form_data,
Add these lines:
data:{action:"search","loc":$("#select_type").val().toString()},
In PHP remove these lines :
foreach ($_POST as $key => $value) {
$_POST[$key] = trim(preg_replace('/\s+/', ' ', ($value)));
}
$arr_val = $_POST;
$loc = $arr_val['loc'];
$action = $arr_val['action'];
And these lines instead:
$loc = $_POST['loc'];
$action = $_POST['action'];
$loc =explode(","$loc );
foreach($loc AS $val)
{
echo $val; // your locations
}
I am trying to submit two dropdown lists with JSON data into my database table. I can get as far as the data inserted into the table but the 'date' and 'time' columns show the ID and parent ID instead of the date and times that are available in the dropdowns. Can anyone tell me why this is? (Main relevant code showing)
<?php
session_start();
include('includes/config.php');
error_reporting(0);
if (isset($_POST['submit'])) {
$arenadate = $_POST['date'];
$arenatime = $_POST['time'];
$useremail = $_SESSION['login'];
$sql = "INSERT INTO tblbooking(userEmail,ArenaDate,ArenaTime) VALUES(:useremail,:date, :time)";
$query = $dbh->prepare($sql);
$query->bindParam(':useremail', $useremail, PDO::PARAM_STR);
$query->bindParam(':date', $arenadate, PDO::PARAM_STR);
$query->bindParam(':time', $arenatime, PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
echo "<script>alert('Booking successful.');</script>";
}
else {
echo "<script>alert('Something went wrong. Please try again');</script>";
}
}
?>
<form action="" method="post">
<div class="contact_form gray-bg">
<div class="form-group">
<label for="" class="control-label">Select Date</label>
<select name="date" id="date" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Date</option>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Select Time</label>
<select name="time" id="time" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Time</option>
</select>
</div>
<?php if ($_SESSION['login']) {
?>
<div class="modal-footer text-center">
<input type="submit" name="submit" value="Confirm Booking"
class="btn btn-xs uppercase">
</div>
<?php } else { ?>
<a href="#loginform" class="btn btn-xs uppercase" data-toggle="modal"
data-dismiss="modal">Login To Book Seat</a>
<?php } ?>
</div>
</div>
</div>
</form>
</div>
</div>
</section>
<script>
$(document).ready(function (e) {
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
get_json_data('date', 0);
$(document).on('change', '#date', function () {
var date_id = $(this).val();
if (date_id != '') {
get_json_data('time', date_id);
} else {
$('#time').html('<option value="">Select Time</option>');
}
});
});
</script>
You are overwriting the empty option in #date so that isn't really needed in the html. You can change the following line from:
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
to:
html_code += '<option value="' + value.avail + '" data-id="'+value.id+'">' + value.avail + '</option>';
The posted value for 'date' and 'time' will be the selected options value attribute, but this will break selecting the date and getting the time based on that id. In this case you could add a data-id attribute and use that to get the time which means the following code would change from:
var date_id = $(this).val();
to:
var date_id = $(this).data('id');
Don't set the value attribute of an <option> tag unless you want the form to receive that value instead of the visible text.
If you write an option like this inside of a <select name="date">:
<option value="">Select an option</option>
Then the POSTing form will deliver $_POST['date'] = ''.
If you write:
<option>Select an option</option>
Then the POSTing form will deliver $_POST['date'] = 'Select an option'.
In terms of form delivery, there is never a need to duplicate the option text as a value.
If you want to store data inside of each <option> tag, I'll give the same advice as aCMoFoCord because data- attributes are clean and flexible regarding the values that they can hold.
Specifically, I'm saying:
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option data-id="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
Then:
$(document).on('change', '#date', function () {
if ($(this).val() != '') {
get_json_data('time', $(this).data('id'));
} else {
$('#time').html('<option value="">Select Time</option>');
}
});