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('');
}
});
})
Related
i have this code for add/remove dynamic input:
JS:
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
var number = Math.random();
return '<td id="' + number + '"><input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" /></td>' + '<td><select name="" class="form-control"><option> Select</option><option> Male</option><option> Female</option></select></td>' + '<td><input name = "DynamicTextBox" type="radio" value = "' + value + '" /></td>' + '<td><input name = "DynamicTextBox" type="checkbox" value = "' + value + '" /></td>'+'<td><input name = "order" type="number" value = "" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="fas fa-times"></i></button></td>'
}
HTML:
<p> </p>
<h5 class="text-center">Dynamic Control : Text Box, Dropdown List, Radiobox and Checkbox</h5>
<section class="container">
<div class="table table-responsive">
<table class="table table-responsive table-striped table-bordered">
<thead>
<tr>
<td>TextBox</td>
<td>Dropdown List</td>
<td>Radio</td>
<td>CheckBox</td>
<td>Order</td>
<td>BTN</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="fas fa-plus"></i> Add </button></th>
</tr>
</tfoot>
</table>
</div>
</section>
this code work true for me but how do can i add dynamic order(from 1 to ...) for each row(td). my mean add order input from number 1 and add +1 number from last order number.
demo is here
update: (my need)
You need to just modify the JS code logic. The below example shows the use of variable count and its usage.
Here, the variable count is declared as 1 initially and as per the "Add" click the count value has been incremented by 1. Same way the count is been decremented by 1 when we are deleting/removing the the "tr" column.
$(function () {
var count = 1;
$("#btnAdd").bind("click", function () {
var div = $("<tr />");
div.html(GetDynamicTextBox("", count));
$("#TextBoxContainer").append(div);
count++;
});
$("body").on("click", ".remove", function () {
$(this).closest("tr").remove();
count--;
});
});
The click function will have one more argument count which is used for the rendering/displaying of the count value in the order field.
function GetDynamicTextBox(value, count) {
var number = Math.random();
return '<td id="' + number + '">
<input name = "DynamicTextBox" type="text" value = "' + value + '" class="form-control" />
</td>' + '
<td>
<select name="" class="form-control">
<option> Select</option>
<option> Male</option>
<option> Female</option>
</select>
</td>' + '
<td>
<input name = "DynamicTextBox" type="radio" value = "' + value + '" />
</td>' + '
<td>
<input name = "DynamicTextBox" type="checkbox" value = "' + value + '" />
</td>'+'
<td>
<input name = "order" type="number" value = "' + count + '" /></td>' + '
<td>
<button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button>
</td>'
}
The above code works when we are removing the row from the last column.
If you are removing in-between the row from the list of tr tags you will find the order columns values are not arranged properly.
The below code is used for the removing the tr tag in-between the row and as well as the from the last tr tag. This code will be flexible for removing the tr row from anywhere in the list as well as updating the order row in the incremental way.
$("body").on("click", ".remove", function () {
var deleteElement = $(this).closest("tr");
var countOfDeleteElement = $(deleteElement).find("#order").val();
var lastElementCount = count - 1;
if (countOfDeleteElement !== lastElementCount) {
// It will come inside this if block when we are removing inbetween element.
var remainingElements = deleteElement.nextAll('tr'); // get all the below elemnts from the removing element.
// updating all remainingElements value of the order column
remainingElements.each((i, ele) => {
$(ele).find("#order").val(countOfDeleteElement);
countOfDeleteElement++;
})
}
deleteElement.remove();
count--;
});
How can I get dynamically added rows id's and user entered data? I have created a dynamic table but I don't know how to get the values and dynamically generated id's. Can anyone please help me?
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if (!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><select class="form-control" id=' + cashacc + ' ' + FieldCount + '></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' ' + FieldCount + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" data-action="sumDebit" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' ' + FieldCount + '/></td><td style="width: 4%"><img src="./img/delete.svg" class="dlt-icon" ' + FieldCount + '></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row" class="jsrow">
<!-- First row -->
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control narate" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" data-action="sumDebit" value="100" class="form-control" name="cashdeb" readonly/>
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly/>
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
</tbody>
</table>
FIDDLE Here..
What do you mean by ids?? on what action you would want user data and ids of dynamically created rows.
Everything is there. You have jsrow enter code hereclass for each tr created. Fetch all tr and then fetch each input value as you have distinct class for each input.
var rows = $('#cashTable').find('tr.jsrow'); // get all rows.
Then iterate rows as per your need. i am writing directly lets say want to get all ids of row 2. Find all inputs under that row as below and then get id attribute.
var inputs = $(rows[0]).find('input'); // all inputs. same way all select as well
// iterate all inputs and grab ID attribute
for(let i =0 ; i< inputs.length; i++ ) {
var attr = inputs[i].getAttribute('id');
console.log(attr); // id attribute
console.log(inputs[i].value); // value
}
You can get user input by referring to the column and row inside a table
var table = document.getElementById("cashTable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseFloat(table.rows[i].cells[5].innerHTML);
//here cells is referred to the cell number you want the value if you want the value of all cells of a row then loop through the cells of a row
}
alert(sumVal);
console.log(sumVal);
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
I want to create a shopping cart where a client select an item from the autocomplete search automatically added to cart.and based on the number of quantity price can be updated. I have added to the cart successfully but I couldn't update the price dynamically.
Can anyone point me out what's the error with the existing code:
$('#searchName').autocomplete({
source: '{!! asset('nameAutocomplete') !!}',
select:function(suggestion,ui){
event.preventDefault();
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price" id="price">' + ui.item.price +
'</td><td><input type="text" id="quantity" value="1"/></td><td><input type="text" id="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
$('#quantity').on('keyup',function(){
var tot = ui.item.price * this.value;
$('#total').val(tot);
});
}
});
Here is the table part code :
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Error I'm getting :
Check with following code,I added little bit to #Mayank code,
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price">' + ui.item.price +
'</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
$('.quantity').on('keyup',function(){
//Corrected part
var tot = $(this).parent().prev().html() * this.value;
//var tot = ui.item.price * this.value;
//Assume that you are getting correct value to tot variable
$(this).parent().next().find('.total').val(tot);
});
Make following changes in code like:
var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
'</td><td class="name">' + ui.item.value +
'</td><td class="price">' + ui.item.price +
'</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');
// Use class in place of id, as you cannot work with id for multiple occurance of same html
$('.quantity').on('keyup',function(){
var tot = ui.item.price * this.value;
$(this).find('.total').val(tot); // Use DOM traverse to get the next <input type="text" /> and put new total value to it
});
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.