Get Ajax response to table's td input - javascript

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);

Related

add dynamic order to add remove html input field

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 to add checkboxes dynamically to the table in 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

Drop down menu not showing JSON array when new row added dynamically

I'm working on dynamically adding new rows and delete new rows with SELECT option. The dynamic row adding and deleting works but the drop down menu doesn't seem to show the JSON array when new row is added. Only the first two static drop down menus shows the JSON array option. Can anyone help figure which part of my code is wrong? Below are my codes and the screenshot:
JavaScript:
<script>
/////////////////ADD and DELETE ROWS///////////////
/************add new row dymnically******************/
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'">'+
'<td>'+
'<select class="pcode" name="project_code[]" >'+
'</select>'+
'</td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn_remove">Delete Row</button></td></tr>');
});
/**************Remove row****************/
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
////////////SHOW JSON DATA ON MULTIPLE DROP DOWN MENU/////////////
$(".pcode").each(function() {
$(this).empty();
$(this).append('<option selected="true" disabled>Choose Project Code</option>');
$(this).prop('selectedIndex', 0); //Default Selected Option
const url = 'api_redcap.php'; //JSON Data source
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
$(".pcode").append($('<option></option>').attr('value', entry.project_code).text(entry.project_code)); // Populate dropdown with list of project code
})
});
});
</script>
HTML code:
<form action="" method="post">
<table id="dynamic_field">
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
<button type="button" name="add" id="add">Add Row</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
HTML Screenshot
#Les88, For example I use static array, You can make json call with my bindOption() function and get data from your service call.
You bind the select tag but there is no code written for binding options inside it i modified it so, Kindly look below solution and let me know is it work for you?
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'">'+
'<td>'+
'<select class="pcode" name="project_code[]" >'+
bindOption() +'</select>'+
'</td>'+
'<td><button type="button" name="remove" id="'+i+'" class="btn btn_remove">Delete Row</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$(".pcode").each(function() {
$(this).find('option').remove();
$(this).append(bindOption());
})
});
function bindOption(){
var options = '<option selected="true" disabled>Choose Project Code</option>';
var serviceArray= new Array("Living Room","Dining Room","Bedroom(s)","Family Room","Kitchen","Den","Hallway(s)","Ste(s)","Bathroom","Landing(s)");
for (var i = 0; i < serviceArray.length; i++) {
options += '<option value="' + serviceArray[i] + '">' + serviceArray[i] + '</option>';
}
return options;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<table id="dynamic_field">
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<select class="pcode" name="project_code[]">
</select>
</td>
<td>
<button type="button" name="add" id="add">Add Row</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="submit">
</form>
You can simply achieve this by
$(document).ready(function () {
const url = 'api_redcap.php'; //JSON Data source
function getOptionsHtml() {
var html = '<option selected="true" disabled>Choose Project Code</option>';
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
html += '<option value="' + entry.project_code + '">' + entry.project_code + '</option>';
})
});
return html;
}
var opionsHtml = getOptionsHtml();
var i = 1;
$('#add').click(function () {
i++;
$('#dynamic_field').append('<tr id="row' + i + '">' +
'<td>' +
'<select class="pcode" name="project_code[]" >' +
opionsHtml+
'</select>' +
'</td>' +
'<td><button type="button" name="remove" id="' + i + '" class="btn btn_remove">Delete Row</button></td></tr>');
});
/**************Remove row****************/
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$(".pcode").each(function () {
$(this).empty();
$(this).append(opionsHtml);
});
});

Enter key to create new row and focus current input field

<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>
<script>
var i = $('table tr').length;
$('.lst').on('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$('.inputs').keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
</script>
In this form initially focus on first text box ,then press enter key it automatically focus to nearby input fields at dead end while we press enter Key then it create new row and focus to initial input field presented in newly created row
after that while we press enter key it doesn't focus to near by text field please help to resolve this issue.
In first row it work correctly while we entering second row it not working
please help
You need event delegation for dynamically generated elements like following.
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="name_' + i + '" id="name_' + i + '" /></td>';
html += '<td><input type="text" class="inputs" name="age_' + i + '" id="age_' + i + '" /></td>';
html += '<td><input type="text" class="inputs lst" name="phone_' + i + '" id="phone_' + i + '" /></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
<td>Age</td>
<td>Phone</td>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="name_1" id="name_1" /></td>
<td><input type="text" class="inputs" name="age_1" id="age_1" /></td>
<td><input type="text" name="phone_1" class="inputs lst" id="phone_1" /></td>
</tr>
</table>

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