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

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

Related

Data Attribute Access from Dynamically Added Select

So far I have only seen examples getting data attribute from a select option that is already on the page, or added after a few seconds.
I'm looking at clicking a button, adding 3+ form fields which the one searchable dropdown field has a data tag in it with other information to use. Maybe I'm not going about it the right way.
This is the generated options on the select
while ($row = mysqli_fetch_array($result))
{
$part = mysqli_real_escape_string($link, $row['part_number']);
$output .= "<option value=" .$row['id']. " data-sellprice=".$row['sell_price'].">" .$part. "</option>";
}
This is the Javscript that is creating the fields.
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><select name="item_name[]" class="form-control fstdropdown-select item_name" id="swoparts"><option value="">Select Unit</option><?php echo fill_unit_select_box($db); ?></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><input type="text" name="item_price[]" class="form-control item_price" /></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);
setFstDropdown();
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$("#swoparts").on("change", "select[name='item_name[]']", function(){
console.log(this.value);
})
});
</script>
I would like to get the data-sellprice from the option and display it in the item_price[] text field and use the amount to to keep adding to the other amounts of the form for a total.
I can make the data attribute work on a select that is already on the page when loaded.
EDITED PART NEED HELP HERE!!!!!!
I have gotten this far, please explain on what I have done and why its not working. I can make this all work for the select that created during the page creation or on document load. I CAN NOT make this work after the fact.
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Item Name</th>
<th>Enter Quantity</th>
<th>Item Price</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
<tr>
<td>
<select id="swoparts" class="swoparts">
<option value="1" data-sellprice="55.00">Some thing we sell</option>
<option value="2" data-sellprice="100.00">Something else we sell</option>
</select>
</td>
<td><input type="text"></td>
<td><input type="text"><td>
</tr>
</table>
$(document).ready(function(){
$('select.swoparts').change(function() {
var e = document.getElementById("swoparts");
var strUser = e.options[e.selectedIndex].value
console.log(strUser);
});
$(document).on('click', '.add', function(){
$("#item_table").last().append('<td><select id="swoparts" class="swoparts"><option value="1" data-sellprice="55.00">Some thing we sell</option><option value="2" data-sellprice="100.00">Something else we sell</option></select></td><td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td><td><input type="text" name="item_price[]" class="form-control item_price" id="sell_price" /></td><td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
});
WHY can't I grab the information from the dynamically generated select?
I want 3 boxes added to my table, with a dropdown that is filled from a database where I can grab the dataset attribute and show it somewhere else and add it together with other dataset attributes from other added table rows.
I have created a fiddle:
Add Select box having option where data-* attribute is there.
Then on change of the these select box value find the selected option
Fetch the above option's data-* attrbite and add it.
https://jsfiddle.net/asutosh/k6jxmgs9/21/
The JS code below:
function addFields() {
const form1 = document.querySelector('#testform')
const selectField = document.createElement('select');
let dataView = null;
[1, 2, 3].forEach((aVal) => {
let optionElem = document.createElement('option');
optionElem.setAttribute("value", aVal);
optionElem.setAttribute("data-sellprice", "sell-" + aVal);
optionElem.text = aVal;
selectField.appendChild(optionElem);
})
selectField.addEventListener('change', () => {
form1.querySelectorAll('option').forEach((opt) => {
if (opt.value === selectField.value) {
dataView = opt.getAttribute("data-sellprice");
}
})
document.querySelector('#selectdData').innerHTML = dataView;
});
form1.appendChild(selectField);

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

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('');
}
});
})

Table data disappearing upon live search

I am generating dynamic textboxes on button click in a table.
On button click i am calling Details() which appends a new row to the table:
function Details(id,name)
{
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="'+ id +'" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="'+ name +'" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
But when i try to live search the data from the table then its rows disappear.
Live Search:
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var id = $(this).find("td").text().toLowerCase().trim();
$(this).toggle(id.indexOf(value) !== -1);
if(id.indexOf(value) !== -1){
count = count+1;
}
});
});
Table:
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
What am i doing wrong?? Any help would be appreciated.
You can use this (edited to use non-ES6 syntax):
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
Explanation
.text() is not meant to grab input vales.
You need to use .val(). But since there can be multiple inputs per rows, you want to check whether at least one cell matches the filter.
.toArray() transforms the set of nodes into an array,
Array#some returns true if at least one cell's value matches the filter string.
Demo using the rest of your code
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
if (rowMatches) {
count = count + 1;
}
});
});
function Details(id, name) {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="' + id + '" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="' + name + '" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
Details(1, 'foo');
Details(2, 'bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
<input id="search_field" placeholder="Filter"/>

Categories