Trouble cloning a set of selects dependent on each other - javascript

I am trying to create a dynamic table that allows the user to select from around 100 variables. These variables have been split into categories and I have been displaying them in a second select that depends on the user selecting a value in the first select. I have been searching the web for answers and have come up blank. I realize that the clone() call will duplicate all data and for that reason id's are a poor choice for the rows.
Here is what I currently have for HTML:
<body>
<table name='myTable' class="dynatable">
<thead>
<tr>
<th class='idCol' >ID</th>
<th>Category</th>
<th>Metric</th>
<th>Conditional</th>
<th><button class="add">Add</button></th>
</tr>
</thead>
<tbody>
<form name='myForm'>
<tr class="first">
<td class="id idCol"><input type="text" name="id[]" value="0" /></td>
<td><select name='categories' onChange='updatemetrics(this.selectedIndex)' style="width: 260px">
<option selected>--Select Category--</option>
<option value='1'>Customer Experience</option>
<option value='2'>Key Satisfaction Identifiers</option>
<option value='3'>Personnel Costs</option>
<!-- I have cut the rest out for the sake of brevity. -->
</select></td>
<!-- This is the select that populates based on the user's choice. -->
<td><select style="width: 310px"name='metrics'></select></td>
</tr>
</form>
</tbody>
</table>
</body>
The Javascript that I am working with is as follows.
$(document).ready(function() {
var id = 0;
// Add button functionality
$("table.dynatable button.add").click(function() {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone(true);
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live("click", function() {
$(this).parents("tr").remove();
});
});
//script for dynamically populating the metrics select
var metricCategories=document.myForm.categories;
var metricList=document.myForm.metrics;
var metrics=new Array()
metrics[0]=" "
metrics[1]=['Wait time average|waitInLine','Mystery Shopper Scores|mysteryScores']
metrics[2]=['Referral Rate|ref_rate','Facebook Shares|facebook_shares','Twitter Followers|twit_followers','Customer Complaint Calls|comp_calls']
metrics[3]=['Pension Payouts|pension_pay', 'Full Time Employees|ftes', 'Part Time Employees|ptes', 'Contractor Costs|contract_costs']
function updatemetrics(selectedMetricGroup){
metricList.options.length=0
if (selectedMetricGroup>0) {
for (i=0; i<metrics[selectedMetricGroup].length; i++)
metricList.options[metricList.options.length]=new Option(metrics[selectedMetricGroup][i].split("|")[0], metrics[selectedMetricGroup][i].split("|")[i])
}
}
Any help would be appreciated. To reiterate the reason I am asking for help, I need to add/ remove rows that hold select nodes that interact with each other. Thanks in advance.

Related

JavaScript, append HTML and reference IDs in function

I have a form that shows a drop-down menu and a text field next to it:
<html>
<body>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select id="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc"></div></td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can select one of the values in the drop-down, and when you enter a numeric value into the text field, on each keyup, it'll display the value multiplied by the selected value. You can also click the "Add another project" link and it'll append/create another drop-down and text field. This already works, and is done with the following Jquery code:
<script type="text/javascript">
$(document).ready(function(){
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = `<tr>
<td scope="row">
<select id="test_project2" name="test_project[]" class="custom-select">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input id="test_value2" name="test_value[]" type="text" placeholder="Enter value"></td>
<td><div id="test_calc2"></div></td>
</tr>`;
$(addProject).click(function(){
$(wrapper).append(projectHTML);
});
});
$('#test_value').keyup(function(){
$('#test_calc').text(Math.round($(this).val() * $("#test_project option:selected").val()));
});
The problem is I can't get the multiplication function to work/display the result for any newly appended lines. Above you can see I tried hardcoding the values of test_value2 and test_calc2 and then added this below:
$('#test_value2').keyup(function(){
$('#test_calc2').text(Math.round($(this).val() * $("#test_project2 option:selected").val()));
});
I would expect the result (at least for one new appended line) to appear in the same way as for the first line, but nothing seems to happen. My goal is to get the results to appear for the appended line, and then also find a way to have that keyup calculation function work for any number of appended lines (rather than hardcode 2, 3, 4, etc. values).
The ids, I think, will need to be dynamically assigned as the lines are appended, and then the name will stay the same to hold the arrays for test_array and test_value which I'm going to receive and process via PHP.
Thanks!
Remove all your IDs from the template rows, use classes or name="" instead as your selectors
Assign an ID to your TBODY, we'll use it as the .on() event delegator
Use the "input" event, not the "keydown" event. You can also copy/paste values, remember?
on "input" - refer to the parent TR using .closest() before descending back (using .find()) to find the elements specific for that row
Use parseInt() or parseFloat() to handle input strings. Also remember to always fallback to a number i.e: 0 to prevent NaN results
jQuery(function($) {
const projectHTML = `<tr>
<td>
<select name="test_project[]" class="custom-select">
<option value="" selected>Select</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</td>
<td><input name="test_value[]" type="type" placeholder="Enter value"></td>
<td><div class="result"></div></td>
</tr>`;
const $projects = $("#projects"); // assign an ID to your tbody
const $addProject = $('.add_project');
const arrRow = () => $projects.append(projectHTML);
// Create new row on click
$addProject.on("click", arrRow);
// Add the first row
arrRow();
// use a delegator which is not dymanic (the TBODY in this case),
// and use delegated events to any ":input" element:
$projects.on("input", ":input", function(ev) {
const $tr = $(this).closest("tr");
const $project = $tr.find('[name="test_project[]"]');
const $value = $tr.find('[name="test_value[]"]');
const $result = $tr.find(".result");
const project = parseInt($project.val(), 10) || 0;
const value = parseFloat($value.val()) || 0;
const result = project * value;
$result.text(result);
});
});
<table>
<tbody id="projects"></tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The IDs must be unique, instead whenever you add another row you duplicate the IDs.
Instead of IDs I changed them to class in order to combine this keyword with .closest() and .find() to get the values of interest.
Moreover, because you add new elements to the table you need to delegate the event.
If you change the select you need to calculate again, not only on typing into the input field.
var addProject = $('.add_project');
var wrapper = $('.project_wrapper');
var projectHTML = '<tr>\
<td scope="row">\
<select class="test_project" name="test_project[]" class="custom-select">\
<option selected>Select</option>\
<option>10</option>\
<option>20</option>\
</select>\
</td>\
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>\
<td><div class="test_calc"></div></td>\
</tr>';
$(addProject).click(function () {
$(wrapper).append(projectHTML);
});
$(document).on('input', '.test_value', function (e) {
$(this).closest('tr').find('.test_calc').text(Math.round($(this).val() * $(this).closest('tr').find('.test_project option:selected').val() || 0));
});
$(document).on('change', '.test_project', function(e) {
$(this).closest('tr').find('.test_value').trigger('input');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody class="project_wrapper">
<tr>
<td scope="row">
<select class="test_project" name="test_project[]">
<option selected>Select</option>
<option>10</option>
<option>20</option>
</select>
</td>
<td><input class="test_value" name="test_value[]" type="number" placeholder="Enter value"></td>
<td>
<div class="test_calc"></div>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="3">
Add another project
</td>
</tr>
</tbody>
</table>

Setting default value in dropdown after changing element jQuery

I apologize in advance if this question/issue was brought up or asked. I did not find one of this type.
On button click, I would like to change the data field into a dropdown list that defaults to the value that was present before the change.
$("#edit").on("click", function() {
let food = $("#food");
let foodValue = food.attr("data-food-value");
food.html(`<select>
<option value="1">Fries</option>
<option value="2">Burger</option>
<option value="3">Pizza</option>
</select>`);
$(`#food select option[value="${foodValue}"]`).attr("selected", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th>Favorite Food</th>
<td id="food" data-food-value="3">Pizza</td>
</tr>
<tbody>
</table>
<button id="edit">Edit</button>
I want it to default to Pizza on button click, but it defaults to Fries. Any help is greatly appreciated. Thank you in advance.

jQuery - .each() over dynamically removed rows - numbering is off

JSFiddle: https://jsfiddle.net/dxhen3ve/4/
Hey guys,
I've been trying to figure out the issue here for some time.
Essentially, I have a table with rows. You can add new rows (works fine). However, on the deletion of rows, I would like to re-number all of the rows below it (including all of their input names/ids within).
This works fine as I have it on the first time you click "remove" for any row.. say, if you have rows 0-4 and delete row 1, you will now have rows 0-3 and they will be numbered correctly--however, after that if you click remove again on another row, the numbers do not update
The indexes are getting mixed up some how and it almost seems like it's not recognizing that I've removed an element from the DOM.. when I console.log the indexes everything looks fine.
As an example:
- Add 5 rows (0-4)
- Remove row #1 (the rows below get updated as they should).
- Remove the new row #1, and you will see that row #2 takes its place instead of changing to row #1.
- In the function 'renumber_budget_rows', the if statement seems to get skipped for that row #2, even though I feel like it should meet the conditions (and is present if I console.log(item)
What am I missing? https://jsfiddle.net/dxhen3ve/4/
** Update: Just wanted to update that I have a true resolution that works, which is great! However, I am more interested in knowing WHY my solution is failing. At the moment, the best I have, from the correct answer, was that my indexes were misaligned. I'm going to take a new look at them.
HTML
<script type="text/template" id="budget_row-template">
<tr id="budget_row-{{index}}" class="budget-row" data-budget-index="{{index}}">
<td class="budget-line">{{index}}</td>
<td><input type="text" name="budget_description-{{index}}" id="budget_description-{{index}}" class="budget-description" /></td>
<td><input type="text" name="budget_amount-{{index}}" id="budget_amount-{{index}}" class="budget-amount" /></td>
<td>
<select name="budget_costcode-{{index}}" id="budget_costcode-{{index}}" class="budget-costcode">
<option>-- Select Cost Code</option>
</select>
</td>
<td><i class="fa fa-share"></i></td>
<td>remove</td>
</tr>
</script>
<div class="table-scroll-container">
<table class="table table-striped table-bordered table-hover tablesorter" id="budget-display">
<thead>
<tr>
<th>Line #</th>
<th>Description</th>
<th>Amount</th>
<th>Cost Code</th>
<th data-sorter="false"></th>
<th data-sorter="false"></th>
</tr>
</thead>
<tbody id="test">
<tr id="budget_row-0" class="budget-row" data-budget-index="0">
<td class="budget-line">0</td>
<td><input type="text" name="budget_description-0" id="budget_description-0" class="budget-description" /></td>
<td><input type="text" name="budget_amount-0" id="budget_amount-0" class="budget-amount" /></td>
<td>
<select name="budget_costcode-0" id="budget_costcode-0" class="budget-costcode">
<option>-- Select Cost Code</option>
</select>
</td>
<td><i class="fa fa-share"></i></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="text-align-center">
<i class="icon icon-plus icon-white"></i> Add Line Item<br />
</div>
JS
function renumber_budget_rows(removed) {
$('#budget-display tbody .budget-row').each(function(indite, item) {
var ti = $(item).data('budget-index');
if( ti > removed ) {
ti--;
//console.log(item);
$(item).attr('id', 'budget_row-'+ti);
$(item).attr('data-budget-index', ti);
$(item).find('.budget-line').html(ti);
$(item).find('.budget-description').attr({ 'name': 'budget-description-'+ti, 'id': 'budget-description-'+ti });
$(item).find('.budget-amount').attr({ 'name': 'budget-amount-'+ti, 'id': 'budget-amount-'+ti });
$(item).find('.budget-costcode').attr({ 'name': 'budget-costcode-'+ti, 'id': 'budget-costcode-'+ti });
$(item).find('.add-budget-child').attr({ 'id': 'budget_row-addparent-'+ti, 'data-budget-index': ti });
$(item).find('.trash-budget-row').attr({ 'id': 'budget_row-'+ti+'-trash' });
$(item).find('.trash-budget-row').attr('data-budget-index', ti);
}
});
}
var budget_index = 0;
$('.add-budget-row').click(function(e) {
budget_index++;
e.preventDefault();
var budget_html = $('#budget_row-template').html();
budget_html = budget_html.replace(/{{index}}/g, budget_index);
$('#budget-display tbody').append(budget_html);
});
$('#budget-display').on('click', '.trash-budget-row', function(e) {
var removed = $(this).data('budget-index');
$(this).closest('tr').remove();
console.log(removed);
renumber_budget_rows(removed);
budget_index--;
});
While you are deleting the row, after a row deletion, you can iterate through every tr using .each() function and change the attributes based on the index i value.
$('#budget-display').on('click', '.trash-budget-row', function(e) {
var removed = $(this).data('budget-index');
$(this).closest('tr').remove();
$('tbody tr').each(function(i){
$(this).find('td').eq(0).text(i);
$(this).attr("data-budget-index",i);
$(this).attr("id","budget-row-" + i);
});
budget_index--;
});
Working example : https://jsfiddle.net/DinoMyte/dxhen3ve/5/

Can't filter datatable by selected value in dropdown

I am using the jQuery plugin DataTables. I have a table of data that has HTML inputs and selects. When I use the DataTable search filter to filter the results and I search for all dropdowns that have the selected value of 'Open', nothing changes.
I believe this is happening because every dropdown in the table has the same options and the filter is searching on them and returning all results, since they all match.
How can I get the filter to search on only the selected value and not all options of the dropdown?
I have tried to find a solution, but all I can find are results like these :
Dropdown filter jquery datatables
CustomFilter
These all deal with adding custom filters for each column, I just want to use the existing DataTable filter.
Example
Live example of the problem, Search for 'Open' or 'Closed'
Code
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="name" type="text" value="Need more memory" id="name1"></td>
<td><select name="status" id="status1">
<option value="2">Closed</option>
<option selected="selected" value="1">Open</option>
</select>
</td>
</tr>
<tr>
<td><input name="name" type="text" value="Can't connect" id="name2"></td>
<td><select name="status" id="status2">
<option selected="selected" value="2">Closed</option>
<option value="1">Open</option>
</select>
</td>
</tr>
</tbody>
</table>
Now, you can use a data-search attribute on the <td>-element with data-tables. ref
<tr>
<td>
<input name="name" type="text" value="Need more memory" id="name1">
</td>
<td data-search="Open">
<select name="status" id="status1">
<option value="2">Closed</option>
<option selected="selected" value="1">Open</option>
</select>
</td>
</tr>
<tr>
fiddle
my similar question on datatables.net
There is a better way to put a drop-down list into your cells. Of course this is searchable. You can watch the offical tutorial about this technique.
Client side
Drop-down list creation
When you initialize the plugin you can do this:
<script type="text/javascript">
$(document).ready(function () {
$('#datatable').dataTable().makeEditable({
sUpdateURL: "UpdateData.php",//Server side file accepting AJAX call.
"aoColumns": [//Column settings.
{},//1st column with default settings.
{//2nd column to a drop-down list.
indicator: 'Saving...',
loadtext: 'Loading...',
type: 'select',//This will make it a drop-down list.
onblur: 'submit',
data: "{'open':'Open','closed':'Closed'}"
}]
});
});
</script>
The key is the data part. Here you can define the options of your list. You can also add this part dinamically via PHP. The syntax is the following for one option.
'variable_sent_to_UpdateData.php':'Text that will be displayed'
Every option should be separated by a comma.
Column names
You can also rename your columns as shown in the offical tutorial so when they passed to the server, DataTables won't name them after the <th> tag:
<script type="text/javascript">
$(document).ready(function () {
$('#datatable').dataTable(
aoColumns: [//Rename columns contained by AJAX call.
{sName: "name"},
{sName: "status"}
]
).makeEditable({
//Previous stuff...
});
});
</script>
Server side
After all, you just have to update your database in UpdateData.php:
$id = $_REQUEST['id'];//The id tag of your table's row.
$column = $_REQUEST['columnName'];//Column where the cell was edited.
$value = $_REQUEST['value'];//The new value.
$columnPosition = $_REQUEST['columnPosition'];
$columnId = $_REQUEST['columnId'];
$rowId = $_REQUEST['rowId'];
switch ($column)
{
case 'name':
//Do SQL update...
echo $value;
break;
case 'status':
//Do SQL update...
echo $value;
break;
default: echo 'Error';
}
It's important to echo (return) the $value variable because:
Indicates that the updating was successful.
This value will be the new value in the table.
If you return something else, it will count as an error message that will be displayed in a pop-up window and no changes will be shown in the table.

Display Hidden Tbody Content with OnClick/A Href Tag

I have various hidden tables that become displayed with onChange events. In the content of one of these tables, I would like to put a hyperlink that will take me back to the previously hidden table. So, to begin with, I have:
<table>
<tbody id="option11" style="display: none;">
<tr>
<td>
<p>
<select name="type" onChange="display(this,'option11a','option11b');">
<option>Please select:</option>
<option value= "option11a">Missed Deadline</option>
<option value= "option11b">Application Down</option>
</select>
</p>
</td>
</tr>
</table>
The onChange associated with this table is:
function display(obj,id11a,id11b)
{
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id11a).style.display = 'none';
document.getElementById(id11b).style.display = 'none';
if ( txt.match(id11a) )
{
document.getElementById(id11a).style.display = 'block';
}
if ( txt.match(id11b) )
{
document.getElementById(id11b).style.display = 'block';
}
}
If the user selects option11a, they are presented with:
<table>
<tbody id="option11a" style="display: none;">
<tr>
<tr>
<td><p>1. Identify missing work.</p></td>
<td><p>2. Contact management.</p></td>
</tr>
</tr>
And, if the user selects option11b, they are presented with:
<table>
<tbody id="option11b" style="display: none;">
<tr>
<tr>
<td><p>1. Contact management.</p></td>
<td><p>2. Refer to Missed Deadline instructions.</p></td>
</tr>
</tr>
So- what I'd like to do is this: Place a hyperlink of some sort in the "Refer to Missed Deadline instructions" that, when clicked, displays the table with tbody id option11a once again.
Let me know if I should better clarify. Greatly appreciate all help! Thanks.
You can do this easily with jquery's .last selector.
http://api.jquery.com/last-selector/

Categories

Resources