How to add checkboxes dynamically to the table in javascript - javascript

I have a problem in how to add checkboxes dynamically to the javascript code. I have different scenario. I am getting data through ajax So I need to add table thead in the javascript rather than the html. But now I want to add Checkboxes to my thead. Indeed I added them but I don't know how to check them all with one checkbox. I write also code for that to select all but thats only working when my thead is in the html. Below is my code and it will give you a clear view. Try to read it in the editor because its a more compicated :)
//Javascript
$(document).ready(function() {
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$('select[name="class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/attendance/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var markup = '';
markup += '<tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 2%" class="align-middle text-center">#</th> <th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Attendance<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Date<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr>';
$.each(data, function(key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]"></td> <td><input type="hidden" value="' + value.id + '" name="id[]">' + value.id + '</td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<td><input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '</td>' + '<td><input type="hidden" value="' + value.created_at + '" name="created_at[]">' + value.created_at + '</td>' + '<td style=" width=12%" class="text-center"> <a><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//For selecting all checkboxes
$(document).ready(function() {
$('#options').click(function() {
if (this.checked) {
$('.checkBoxes').each(function() {
this.checked = true;
});
} else {
$('.checkBoxes').each(function() {
this.checked = false;
});
}
});
});

The issue is the execution of event handlers on DOM elements.
The browser renders and executes code from top to bottom (in most cases).
This means that you execute $('#options').click() before you add all checkboxes via Ajax request.
Therefore you are trying to attach an event handler to elements which are not present at that moment of time.
To make it work, you have to add an event listener to the parent element
$('table[id="studentsData"]').on('click', '#options', function() {})
Source:
http://api.jquery.com/on/
The second argument is a selector you are going to target

Related

Get Ajax response to table's td input

I'm trying to retrieve Ajax response to <td> row input but it's not working as expected, it's binding to input but when trying to add another product to row it's replacing previous one.
Example 1:
In above example as you can see first I have added "Camera" to the row and then trying to add another product i.e "Mobile" but it's replacing first one.
Then I have tried another approach but it's not retrieving data in input field.
Example 2:
In above example it's successfully adding data to the next row but it's not editable.
HTML:
<div class="table-responsive">
<table class="table table-bordered table-condensed" id="mytable">
<div class="row">
<div>
<input type="text" id="search" class="form-control"> //To search product by id
</div>
<div>
<button type="button" name="add" id="add" class="btn btn-success">Add Row</button>
</div>
</div>
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tr>
<td><input type="text" name=" addmore[0][name]" id="pname" class="form-control"/></td> //This part commented in Example 2
<td><input type="text" name="addmore[0][qty]" id="qty" class="form-control"/></td> //This part commented in Example 2
<td><input type="text" name="addmore[0][price]" id="price" class="form-control"/></td> //This part commented in Example 2
</tr>
</table>
</div>
Script to retrieve data (Example 1):
<script>
$('#search').on('keydown', function(e) {
if(e.which == 13){
var proid = $("#search").val();
//alert(proid);
$.ajax({
url: '{{ URL::to('search-product/')}}'+"/"+ proid,
type: "Get",
dataType:"json",
success: function (response)
{
$.each(response, function (i, item) {
$('#pname').val(item.product_name);
$('#qty').val(1);
$('#price').val(item.product_price);
});
}
});
}
});
</script>
Script to retrieve data (Example 2):
<script>
$('#search').on('keydown', function(e) {
if(e.which == 13){
var proid = $("#search").val();
//alert(proid);
$.ajax({
url: '{{ URL::to('search-product/')}}'+"/"+ proid,
type: "Get",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.product_name +
'</td><td>' + '1' +
'</td><td>' + item.product_price +
'</td></tr>';
});
$('#mytable').append(trHTML);
}
});
}
});
</script>
Script to add and remove rows:
<script type="text/javascript">
var i = 0;
$("#add").click(function(){
++i;
$("#mytable").append('<tr><td><input type="text" name="addmore['+i+'][name]" class="form-control" /></td><td><input type="text" name="addmore['+i+'][qty]" class="form-control" /></td><td><input type="text" name="addmore['+i+'][price]" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
</script>
In response to my comment, replace in the 2nd example:
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.product_name +
'</td><td>' + '1' +
'</td><td>' + item.product_price +
'</td></tr>';
});
$('#mytable').append(trHTML);
with:
$.each(response, function (i, item) {
trHTML += '<tr>' +
'<td><input type="text" name=" addmore[0][name]" id="pname' + item.product_name + '" class="form-control" value="' + item.product_name + '"/></td>' +
'<td><input type="text" name=" addmore[0][qty]" id="qty' + item.product_name + '" class="form-control" value="1"/></td>' +
'<td><input type="text" name=" addmore[0][price]" id="price' + item.product_name + '" class="form-control" value="' + item.product_price + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);

How to add dynamic change input value

I have problem. I use jquery to make dynamic input in php like this:
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function(){
count += 1;
$('#container').append(
'<tr class="records">'
+ '<td ><div id="'+count+'">' + count + '</div></td>'
+ '<td><select class="form-control form-control-sm" name="site' + count + '" required><option value="">Input Item</option><option value="canon">canon</option><option value="nikon">nikon</option><option value="fuji">fuji</option></select></td>'
+ '<td><input name="codeitem' + count + '" type="text"></td>'
+ '<td><a class="remove_item" href="#" >Delete</a>'
+ '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden"></td>'
+ '</tr>'
);
});
$(".remove_item").live('click', function (ev) {
if (ev.type == 'click') {
$(this).parents(".records").fadeOut();
$(this).parents(".records").remove();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="id_form" action="save.php" method="post">
<table>
<tr>
<td>
<input type="button" name="add_btn" value="Add" id="add_btn">
</td>
</tr>
<tr>
<td>No</td>
<td>Item</td>
<td>Code Item</td>
<td> </td>
</tr>
<tbody id="container">
<!-- nanti rows nya muncul di sini -->
</tbody>
<tr>
<td>
<input type="submit" name=submit value="Save">
</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</form>
Condition: If I chose canon in combo select menu, then at input codeitem show code of the item (in another case, I use PHP to get codeitem from SQL table.
At first row input field, that was success.. but, if I want add more input field with click 'add button' to entry another item (at second row input field), why first input codeitem change code item, not input codeitem at second row?
How can I input dynamic item with that condition?
If you are not working on a legacy code base then it is batter to use latest version of Jquery.
'<td ><div id="'+count+'">' + count + '</div></td>' , you can't use same id in multiple time, so change it to class.
'<td><input name="codeitem' + count + '" type="text"></td>' ,input field name should be fixed in order to process it in your php script after form submit but as you need to get multiple value make it an array codeitem[]
what is the use of rows[] input field?
To input codeitem dynamically on change combo select menu, you have to use "Ajax" to get the 'codeitem' value of the selected combo menu from your database.
Check this jsfiddle .
$(document).ready(function() {
$("#add_btn").click(function(){
let count = $('tr.records').length+1;
$('#container').append(
'<tr class="records">'
+ '<td ><div class="count">' + count + '</div></td>'
+ '<td><select class="site form-control form-control-sm" name="site[]" required><option value="">Input Item</option><option value="canon">canon</option><option value="nikon">nikon</option><option value="fuji">fuji</option></select></td>'
+ '<td><input class="codeitem" name="codeitem[]" type="text"></td>'
+ '<td><a class="remove_item" href="#" >Delete</a>'
+ '<input class="rows" name="rows[]" value="'+ count +'" type="hidden"></td>'
+ '</tr>'
);
});
$(document).on('click',".remove_item", function (ev) {
$(this).parents(".records").fadeOut();
$(this).parents(".records").remove();
//Re-arrange the Row Serial No
$('tr.records div.count').each(function(index) {
$(this).text(index+1)
});
});
$(document).on('change',".site", function (ev) {
let site = $(this).val();
let current = $(this).parents(".records");
if(site!=''){
//make an ajax call to get the corresponding CodeItem of the selected site
/* $.ajax({
url: "/yoururl",
data:{"id":site},
success: function(result){
$(current).find('.codeitem').val(result);
}
}); */
}else{
$(current).find('.codeitem').val('');
}
});
})

How to dynamic continues increase the number of html table in PHP

I have a html table which data is retrieved from database after that i can add new row to enter the data but the nummbering wont continues of last number, my question is how to increasing the numbering of the table, please see the pictere :http://imgur.com/quB1R2G
This is my javascript when the button + clicked the new row will append to the table
$('#btn_add_dependents').click(function(){
var i = 0;
i +=1;
$('#tbl_dependents_info').append(
'<tr class="odd"><td style="margin-left:10px;text-align:center;" class="no"></td> '
+'<td style="text-align:center;"><input id="dependents_name' + i + '" name="dependents_name[]" type="text" size="15" ></td>'
+'<td style="text-align:center;"><select id="dependents_gender'+ i + '" name="dependents_gender[]">'
+'<option value="1">Male</option>'
+'<option value="2">Female</option></select></td>'
+'<td style="text-align:center;"><select id="dependents_relationship'+ i + '" name="dependents_relationship[]">'+ relationship +'</select></td>'
+'<td style="text-align:center;"><input id="dependents_occupation' + i + '" name="dependents_occupation[]" type="text" size="15" ></td>'
+'<td style="text-align:center;"><input id="dependents_dob' + i + '" name="dependents_dob[]" type="date" ></td>'
+'<td style="text-align:center;"><input id="dependents_remark' + i + '" name="dependents_remark[]" type="text" size="20" ></td>'
+'<td style="text-align:center;"><img src="images/subtract.png" style="height:20px;" id="del" ></td>'
+'</tr>');
updateRowOrder();
return false;
});
function updateRowOrder() {
$('td.no').each(function (i) {
$(this).text(i + 1);
});
}
$( document ).on( "click", "#del", function() {
$(this).parent().parent().remove();
updateRowOrder();
});
});
This is function of retrieved the data from database and put in html table
$sql="SELECT name,gender,cust_dependent.relationship as relationship_id,relationship.relationship,occupation,d_o_b,remark
FROM cust_dependent
INNER JOIN relationship ON relationship.id = cust_dependent.relationship
WHERE cust_id = $customer_id AND createdby = $user_id ";
$query=$db->query($sql);
while ($row=$db->fetch_assoc($query)){
$i++;
$name=$row['name'];
$gender=$row['gender'];
$relationship_id = $row['relationship_id'];
$relationship=$row['relationship'];
$occupation=$row['occupation'];
$d_o_b=$row['d_o_b'];
$remark=$row['remark'];
$relationship=$slctrl->getSelectRelationship($relationship_id);
echo<<<EOF
<tr>
<td style="text-align:center;">$i</td>
<td class="odd" style="text-align:center;"><input id="dependents_name$i" name="dependents_name[]" type="text" size="15" value="$name"></td>
<td class="odd" style="text-align:center;"><select id="dependents_gender$i" name="dependents_gender[]">
<option value="1" $male>Male</option>
<option value="2" $female>Female</option></select></td>
<td class="odd" style="text-align:center;"><select id="dependents_relationship$i" name="dependents_relationship[]">$relationship</select></td>
<td class="odd" style="text-align:center;"><input id="dependents_occupation$i" name="dependents_occupation[]" type="text" size="15" value="$occupation" ></td>
<td class="odd" style="text-align:center;"><input id="dependents_dob$i" name="dependents_dob[]" type="date" value="$d_o_b"></td>
<td class="odd" style="text-align:center;"><input id="dependents_remark$i" name="dependents_remark[]" type="text" size="20"value="$remark" ></td>
EOF;}}
I can add the row now but the numbering is wrong its will start as 1, how to let it became continue number of last row?
ps:last row data is retrived from database.
You need to preserve the value(value here indicates number of rows present in your html table). When you retrieve the rows from database , then save the count in some variable , say $count. Set this $count variable in html input field(make it hidden) as
< input type="hidden" id="table-count" value="$count">
And in jquery
while adding row , do
$currentRowNo = parseInt($('#table-count').val())++; //get value
$('#table-count').val($currentRowNo) // update value
while deletion, simply subtract the value
$currentRowNo = parseInt($('#table-count').val())--; //get value
$('#table-count').val($currentRowNo) // update value
Try:
function updateRowOrder() {
var i = 1;
$('td.no').each(function () {
$(this).text(i);
i++;
});
}
Try increasing your index value on click of + button from the last index value you got from database.
You can preserve the last index value you got from database in a hidden field and also update this value on every click on + button.

jQuery UI datepicker function calling dynamically

This is function which is reposible for create row dynamically.
$(document).ready(function() {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function() {
$('#myTable tbody').append('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdateid="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>');
count++;
});
});
now I want to attach this function with the field "Payment Date" as I need the datepicker dynamically
.
$(function() {
$( "#datepicker" ).datepicker({
inline: true
});
});
I have to mentioned here customizing the append function is not possible .
Since it is a widget, you need to initialize it once the element is added to the dom.
So
Use appendTo() to get back the tr that is added
use class for the datepicker instead of id since ID of an element must be unique
after appending the tr find the datepicker element and initialize the widget
Try
$(document).ready(function () {
var count = 1;
var row = $("table#myTable tr:eq(1)");
$(document).on('click', '#addrow', function () {
var $tr = $('<tr class="prototype" id="' + count + '"> <td align="center" ><input type="text" size="10" name="grnno[' + count + ']" id="grnno" class="required" align="right"/></td><td align="center" ><input type="text" name="paymentdate classs="datepicker size="10" class="datepicker" align="right" /></td><td align="center"><select id="bankname" name="bankname"><option value="">Select Bank Name</option><option value="SBI">SBI</option><option value="UBI">UBI</option><option value="UCO">UCO</option><option value="HDFC">HDFC</option></select></td><td align="center" ><input type="text" name="amount[' + count + ']" id="amount[' + count + ']" size="10" class="required" align="right"/></td><td align="center"><input type="button" value="Delete" onclick="deleteRow(this)"></td><td style="display:none;"><input type="text" name="id[]" value="' + count + '" class="id" /></td></tr>').appendTo('#myTable tbody');
$tr.find(".datepicker").datepicker({
inline: true
});
count++;
});
});

Posting html values in Jquery to Controller

I have the following script which contains html data appended to it :
<script>
$(document).ready(function(){
$('#drug_id').change(function (){
option = $(this).find('option:selected').val();
html='';
htmlhead='';
// alert(option)
$.ajax({
type:"GET",
url:"<?php echo base_url();?>transactions/details_now/"+option,
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
// alert(data[i].commodity_name)
html += '<form action="<?php echo base_url()?>transactions/issues" method="post"><tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name' + i +'" value="'+data[i].commodity_name+'"/></td>\n\
<td><input type="text" id="transaction_type' + i + '" name="transaction_type' + i +'" value="'+data[i].transaction_type+'"/></td>\n\
<td><input type="text" id="Available_Quantity' + i + '" name="Available_Quantity' + i +'" value="'+data[i].Available_Quantity+'"/></td>\n\
<td><input type="text" id="Quantity_Ordered' + i + '" name="Quantity_Ordered' + i +'" value="'+data[i].Quantity_Ordered+'"/></td>\n\
<td><input type="text" id="batch_number' + i + '" name="batch_number' + i +'" value="'+data[i].batch_number+'"/></td>\n\
<td><input type="text" id="date' + i + '" name="date' + i +'" value="'+data[i].date+'"/></td>\n\
<td><input type="text" id="username' + i + '" name="username' + i +'" value="'+data[i].username+'"/></td>\n\
</tr> <input type="submit" value="Issue"></form>';
}
htmlhead+='\n\
<th>Commodity Name</th>\n\
<th>Transaction Type</th> \n\
<th>Batch Number</th> \n\
<th>Available Quantity</th> \n\
<th>Ordered Quantity</th> \n\
<th>Department</th>\n\
<th>Requestor Name</th>\n\
';
$('#thead').append(htmlhead);
$('#you').append(html);
},
error:function(data){
}
})
});
});</script>
I want to post the values in the input fields to the controller when I click the issue button.How can I do this?
Try something like
//delegated submit handlers for the forms inside the table
$('#you').on('submit', 'form', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('someurl', $(this).serialize(), function () {
//success do something
}).fail(function () {
//error do something
})
})

Categories