Drop down list from database php/html/javascript - javascript

I want to create a dropdown list from database with javascript.
I am trying to make a dynamic form where I can add multiple rows using "add more" button.
My html form contains an input type text and a drop down list
in html
<form id="add_name" name="add_name">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<select class="form-control" name="nom_ar">
<?php
while ($row2 = $result2->fetch_assoc()){
echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']." </option>";
}
?>
</select>
</td>
<td><input type="text" name="name[]" placeholder="insert name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">add more</button></td>
</tr>
</table>
</form>
In the javascript code I added only the input type text and I don't know how to add the dropdown list like the next code shows :
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select class="form-control" name="nom_ar"><?php while ($row2 = $result2->fetch_assoc()){echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']."</option>";} ?></select></td><td><input type="text" name="name[]" placeholder="Ingredient" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
}
How can I do it? My drop down list in js is always empty. I'm struggling as I'm a beginner. where should I put the php code?

Well, this is your JS code
<script type="text/javascript">
$('#add').click(function() {
$("#dynamic_field").append("<tr></tr>");
$.post("server.php", {
object_field: "Any data",
}, function(server_data) {
$("#dynamic_field tr:last-child").html(parse_server_data(server_data));
});
});
function parse_server_data(data) {
data = JSON.parse(data);
var output_string = "<td><select>";
for (var key in data) {
var value = data[key];
output_string += "<option value=" + key + ">" + value + "</option>";
}
output_string += "</select></td>";
return output_string;
}
</script>
I intentionally segregated server-side code (server.php file) and js code. Why? You should not mix code from server-side and client-side, use power of ajax technologies.
Add to server.php your code that echo's all necessary data (in your case - your fetch_assoc). Learn about MVC model https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
I also added JSON.parse function. JSON is standard of data compression and submission, check json_encode/json_decode functions in PHP and use them
Don't use tables a lot, practice divs/spans

Related

Sending selective data from dynamic table

I have a dynamic table with some data and total counting with JS, when checkbox is ticked row is removed from count.
I need a way to send first ID field and total price to another php page for rows where checkbox is ticked.
As seen on picture below I need to send vales 8, 10 and 15 with total 1500.
I have given every checkbox an unique id and value of same id.
<table id="price-list">
<tr>
<td>Some data</td>
<td>
<input class="w3-check" type="checkbox" checked="" value="<?php echo $row['rad_id']?>" id="<?php echo $row['rad_id']?>">
</td>
</tr>
<tfoot>
<tr class="totalColumn">
<td><span> Ukupno:</span></td>
<td class="total price">0.00 kn</td>
</tr>
</tfoot>
</table>
Closest that I got is reading whole table with JS, with another script putting it into submit value and passing it into another PHP page.
<form action="spec-provjera.php" method="POST">
<input type="button" id="bt" value="Show Table Data" onclick="showTableData()" />
<!-- <input type="submit" name="submit" value="info" id="info" onclick="myFunction()"/> -->
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('price-list');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.value = info.innerHTML + '<br />'; // ADD A BREAK (TAGG)
}
}
</script>
<script>
function myFunction() {
var info = document.getElementById("info").value;
$.ajax({
type : "POST", //type of method
url : "spec-provjera.php", //your page
data : { info : value.info},// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>
<button class="w3-btn w3-right w3-deep-orange" type="submit" name="izrada" id="info" onclick="myFunction()"/>KREIRAJ test</button>
</form>
This passes all table contains into spec-provjera.php with AJAX but this way is totally messy and posts all rows with check-boxes all set too checked.
Id be happy if I could just filter out cheeked row's.
Can someone suggest a way to do this, keep in mind I'm not very good with JS.
Found a solution:
I wrapped whole table as form then made dynamic checkbox unique field and same value "da" like this:
<input class="w3-check" type="checkbox" checked="" name="<?php echo $row['rad_id']?>" value="da">
Also made an total price field an input with read only like this:
$("tfoot .total.price",tbl).html( '<input type="post" id="total" readonly size="5" value="' + t.toFixed(2) + '" name="total"> kn');
Then I'm doing on other PHP page this:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'</br> " ;
}
Witch if i uncheck id 14 as seen on first picture gives me:
POST parameter '8' has 'da'
POST parameter '10' has 'da'
POST parameter '15' has 'da'
POST parameter 'total' has '1500.00'
As seen i have only checked items with total price. Now i can manipulate this as needed in PHP.

Calculate values in multiple tables with records

User can create tables and add records to it. When records added another values must be calculated. I tried to do that with jQuery but something is wrong and do not work. Maybe someone can help me and say how to do that.
Part from blade template (full template: https://pastebin.com/Mdq8fCnJ):
#foreach($tables as $table)
#foreach($table->fuelAccountingRecords as $record)
<tr>
<td id="name">{{ $record->name }}</td>
<td id="liters">{{ number_format($record->liters, 2, '.', '') }}</td>
<td id="show_kilograms"></td>
<td id="show_price"></td>
<td>
<input type="hidden" name="record_id"
value="{{ $record->id }}">
<button type="submit" class="btn btn-danger btn-sm"
name="deleteRecord">Trinti
</button>
</td>
</tr>
#endforeach
#endforeach
And jQuery code:
$(document).ready(function () {
var total_kilograms = $('#total_kilograms').val();
$('#show_kilograms').text(total_kilograms);
$('[data-table-id]').on('click', function () {
$('#table-' + $(this).data('table-id')).append(
'<tr class="child">' +
'<td><input type="text" class="form-control" name="name" autocomplete="off" required autofocus></td>' +
'<td><input type="text" class="form-control" name="liters" autocomplete="off" required></td>' +
'<td>-</td>' +
'<td>-</td>' +
'<td><button type="submit" class="btn btn-primary btn-sm" name="saveRecord">Išsaugoti</button></td>' +
'</tr>'
);
});
});
Another jQuery lines I am using to add rows to table where user can add records. I can not get a value from table and then ouput it or calculate. Help me to fix it.
Empty fields must be filled with values

How to insert autocomplete jquery in innerhtml generated textbox

The autocomplete jquery shows list of all users in the database, when atleast 2 characters are entered in the textbox. The autocomplete is working on a normal input field, but when genereated through innerHTML it is not working.
The autocomplete is working on the following field:-
<input type="text" id="j_d_permit_by[]" name="j_d_permit_by[]" >
A click on the button will add other fields as well calling the addjobdesc function:-
<img src="images/add.png" width="12" height="12"> Add New Job Description<br />
The function:-
function addjobdesc() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<table id="tblObs" name="tblObs" width="70%" bgcolor="#CCCCCC"><tr bordercolor="#FFFFFF">
<td colspan="5"><b>Job Description (Work Ppermit/ Activity)</b></td></tr>
<tr bgcolor="#33CC00">
<td ><center> <b>Exact Location</b> </center></td> <td><b><center>Permit Initiated By<br />/<br />Activity Supervised by</center></b></td>
<td><b><center>Permit Accepted By<br />/<br />aActivity Executor</center></b></td><td><b><center>For What Permit Issued</center></b></td>
<td><b><center>Observation</center></b></td></tr>
<tr><td><center><select name="s_area[]" id="s_area" onchange="addSubArea()">
<option value="0">Chose Sub Area</option></select></center></td>
<td><input type="text" id="j_d_permit_by_add" name="j_d_permit_by[]"></td>
<td><center><select id="j_d_accept_by[]" name="j_d_accept_by[]" ><option value="0">Select User</option><?php $users = getUserS();
while($usersss = mysql_fetch_array($users)){ ?>
<option value="<?php echo $usersss[0];?>"><?php echo $usersss[4]." ".$usersss[5]; ?></option>
<?php } ?>
</select></td>
<td><center><textarea name="permit_ref[]" cols="30"> </textarea></center></td>
<td><center><textarea name="obs_permit[]" id="obs_permit" cols="30"></textarea></center></td></tr></table><input class="submit" type="button" value="Remove" onclick="removeR0ow__(this)">';
<!--<input type="hidden" name="j_d_Location[]" id="j_d_Location" value="" /><input type="text" name="area_Location[]" id="area_Location" value="" readonly="readonly" />-->
document.getElementById('job_desc').appendChild(div);
jQuery(document).ready(function(){
$('#j_d_permit_by_add').autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
var Max_Length = parseInt(document.getElementsByName('s_area[]').length)-1;
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = '';
document.getElementsByName('s_area[]').item(Max_Length).innerHTML = document.getElementById('sarea_div').innerHTML;
}
I want the autcomplete to work on the generated j_d_permit_by[] field in the innerHTML.
Really appreciate your help.
You have bind the autocomplete in jQuery(document).ready but at that time there is no input exists with id =j_d_permit_by_add and hence the function is not bind to the input. You are generating the input dynamically so you have to bind autocomplete function in following way..
Try this to Bind the autocomplete function:
jQuery(document).ready(function(){
$(document).on('#j_d_permit_by_add', selector, function() {
$(this).autocomplete({
source: 'suggest_name.php',
minLength:2
});
});
});
You can refer https://stackoverflow.com/a/25114244/1659563
#Guruprasad is also right, you can bind the autocomplete function after the input is generated dynamically in function addjobdesc()

Total of a particular column from html table having multiple rows

My Java Script Code
<script>
$(function(){
$('#addRow').click(function(){
var html = $('#row_template').html();
$('#dataTable').append(html);
$(".tablerow").each(function(index) {
$(this).html(index + 1);
});
});
$('#deleteRow').click(function(){
$('#dataTable .mychkbox:checked').parents('tr').remove();
});
$('#dataTable').on('change','.select-desc',function(){
var cur_val = $(this).val();
$(this).parents('tr').find('input[name="rate[]"]').val(cur_val);
});
$('#dataTable').on('keyup','input[name="qty[]"]', function(){
var qty = +$(this).val();
var unit = +$(this).parents('tr').find('input[name="rate[]"]').val();
$(this).parents('tr').find('input[name="amt[]"]').val(qty*unit);
var totamt = 0 ;
var theTbl = document.getElementById('dataTable');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
totamt = totamt + theTbl.rows[i].cells[4].InnerHTML;
}
}
});
});
</script>
My HTML Code is
<!DOCTYPE html>
<html>
<div class="left">
<h2><span class="orange">Work Order Items</span></h2>
<table>
<tr>
<td><input type="button" value="Add Row" id="addRow" /></td>
<td><input type="button" value="Remove Row" id="deleteRow" /></td>
</tr>
</table>
</div>
<table id="dataTable" class="form" border="0" width='100%'>
<tr>
<td></td>
<td>No</td>
<td>Item Description</label></td>
<td>Qty</td>
<td>Rate</td>
<td>Amount</td>
<td>Cert No</td>
<td>C Date</td>
</tr>
</table>
<table id="row_template" style="display:none">
<tr>
<td><input type="checkbox" name="chk[]" class="mychkbox" /></td>
<td class="tablerow"></td>
<td>
<?php
$sql = "SELECT itrate,CONCAT(itname,'|',itcode) as mname FROM ITMAST ";
$result = mysql_query($sql) or die(mysql_error());
echo "<select name='itname[]' id='itname' class='select-desc' >";
echo "<option value=''>-- Select Item --</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value = '{$row['itrate']}'";
if ($pitcode == $row['itrate'])
echo "selected = 'selected'";
echo ">{$row['mname']}</option>";
}
echo "</select>";
?>
</td>
<td><input type="text" name="qty[]" id="qty" size="6" class='rightJustified'></td>
<td><input type="text" name="rate[]" id="rate" size="8" class='rightJustified' readonly></td>
<td><input type="text" name="amt[]" id="amt" size="9" class='rightJustified' readonly></td>
<td><input type="text" maxlength="10" size="8" name="txtcertno[]"></td>
<td><input type="date" maxlength="10" size="10" name="txtcdate[]"></td>
</tr>
</table>
</html>
I am trying to take total of amount column i.e. amt[] after each entry of a row, but I am not getting it properly, I have written Javascript function for the same but some thing may be wrong in it
I did not correct all of your mistakes,
You should check #Samurai answer for more details (such as use of the 'id' and other things)
Main problem was, as I said in comment, use of innerHTML which returned "
another thing, your theTbl var was not good, you could never call .length on it. To solve that, you had to handle it this way :
var totamt = 0 ;
var theTbl = $('#dataTable');
//You are using jquery, so use jquery selectors...
var trs = theTbl.find("input[name='amt[]']");
//find there the AMT[] INPUTS, not the rows...
console.log("how many amt inputs? : "+trs.length);
for(var i=0;i<trs.length;i++)
{
//fetch the inputs, and make your calculations here
console.log("amount from row "+i+" = "+trs[i].value);
//do not forget, as Samurai said, to convert html to numeric...
$("#total").html(totamt+=parseFloat(trs[i].value));
}
Here is a working solution :
http://jsfiddle.net/nxm0ye54/20/
First to point out a few mistakes:
$('#row_template').html(): browsers automatically add tbody to the table, so you end up having multiple tbody in your main table which of course won't cause any problem on its own, if that's the desired output.
You're misusing ID. Each tr has multiple td with inputs that share the same ID. Instead you should use class.
To calculate the total amount you're getting the innerHTML of the cells which don't hold a number, but an input element. Instead you want the value these input elements are holding.
You need to convert the values to numbers before doing math on them, otherwise it will assume they're string and just put them beside each other. (e.g. 0+1+2 = 012 and not 3). You should use parseInt or parseFlout which the latter suits this case better.
A few modifications to your code:
$('#addRow').click(function () {
var html = $('#row_template tbody').html();
$('#dataTable tbody').append(html);
And - since you're using jQuery - I completely changed the calculation to a jQuery version:
//gt(0) cause the first row contains headers
//eq(5) cause we want the 6th cell (Amount)
var totamt = 0;
$('#dataTable tr:gt(0)').each(function() {
var newAmt = $(this).find('td:eq(5) input[type=text]').val();
totamt += parseFloat(newAmt);
});

Remove/delete part of hidden field value on button click

I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}

Categories

Resources