jquery datatable edit table row data using form - javascript

var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
tb.row.add([typeName, amount]).draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
</tr>
</thead>
</table>
i need to append edit and delete button for every row. when click the edit button, row data should load to dropdown and textbox. can u guide me to do this ?

With certain changes to the architecture of your app, I would suggest the following approach that employs native DataTables options and API methods:
//initialize DataTable
const tb = $('#example').DataTable({
//remove non-essential controls for the sake of cleaner view
dom: 't',
//use columns option to setup header titles
columns: [
{title: 'Type'},
{
title: 'Amount',
//user 'render' to append Edit/Delete buttons for each entry
render: data => `${data}<button action="delete">Delete</button><button action="edit">Edit</button>`
}
]
});
//click handler for dual purpose 'Submit' button that adds new rows and submits edits
$('#submit').on('click', function() {
//when submit button acts to append new row to the table (default)
if($(this).attr('action') == 'addRow'){
tb.row.add([$("#type").val(), $("#amount").val()]).draw();
}
//when submit button acts to submit edits
if($(this).attr('action') == 'confirmEdit'){
//change affected row data and re-draw the table
tb.row($(this).attr('rowindex')).data([$("#type").val(), $("#amount").val()]).draw();
}
//clean up form, switch it to default state
$('#type').val("");
$('#amount').val("");
$('#submit').attr('action', 'addRow');
});
//'Delete' button click handler
$('#example').on('click', 'tbody tr button[action="delete"]', function(event){
tb.row($(event.target).closest('tr')).remove().draw();
});
//'Edit' button click handler
$('#example').on('click', 'tbody tr button[action="edit"]', function(){
//get affected row entry
const row = tb.row($(event.target).closest('tr'));
//get affected row().index() and append that to 'Submit' button attributes
//you may use global variable for that purpose if you prefer
$('#submit').attr('rowindex', row.index());
//switch 'Submit' button role to 'confirmEdit'
$('#submit').attr('action', 'confirmEdit');
//set up 'Type' and 'Amount' values according to the selected entry
$('#type').val(row.data()[0]);
$('#amount').val(row.data()[1]);
});
tbody tr button {
display: block;
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<label>Type</label>
<select id="type">
<option value="" selected></option>
<option value="Type 01">Type 01</option>
<option value="Type 02">Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="submit" action="addRow">Submit</button>
<table id="example" class="display" cellspacing="0" width="100%"></table>

Add your HTML directly. I've added button, you can similarly add a drop down too. Consider the following:
var tb = $('#example').DataTable();
$('#addRow').on('click', function() {
var typeName = $("#type option:selected").val();
var amount = $("#amount").val();
var row = tb.row.add([typeName, amount, "<span><button>Edit</button><button>Delete</button></span>"]).draw();
var edit = row.node().getElementsByTagName("button")[0];
edit.onclick = function() {
document.getElementById('typeEdit').value = row.data()[0];
document.getElementById('amtEdit').value = row.data()[1];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<label>Type</label>
<select id="type">
<option> Type 01</option>
<option> Type 02</option>
</select>
<label>Amount</label>
<input type="text" id="amount" />
<button id="addRow"> Add </button>
<br/ >
<br/ >
Edit Type
<select id="typeEdit">
<option> Type 01</option>
<option> Type 02</option>
</select>
Edit Amount
<input id="amtEdit" />
<br/ >
<br/ >
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Ops</th>
</tr>
</thead>
</table>

RowEditor.js
I had a similiar issue and wrote a tiny JS tool, that targets editing of rows inline. The repo can be found here. I think its functionality is best described by the picture below, but you can also find a running example here.
Setting it up
What you have to do to integrate it, is
Download and integrate the file
<script type="text/javascript" charset="utf8" src="/js/RowEditor.js"></script>
Set up a configuration about which columns shall be editable and if they should be editable as dropdown or input (compare it to the example picture, you will quickly figure out what it does):
"1":{"type":"input"},
"2":{"type":"input"},
"3":{"type":"select",
"options":{
"1":{"value":'Sales Assistant', "title":'Sales Assistant'},
"2":{"value":'Tech Lead', "title":'Tech Lead'},
"3":{"value":'Secretary', "title":'Secretary'},
"4":{"value":'Developer', "title":'Developer'},
"5":{"value":'Trainee', "title":'Trainee'}
}
}
}
Call the editor, after you have initialized your DataTable:
$(document).ready( function () {
table = $('#table').DataTable();
rowEditor = new RowEditor('#table', table, editRowSettings);
});
Call the function editRow of rowEditor (or however you have named it above) with the index of the row you want to edit. I have the button placed in a sepperate column of the datatable, but you can call it anyway you want it.
<button onclick="rowEditor.editRow(1)">Edit</button>
If you have questions, feel free to ask or issue a pull request :)

Related

Using JavaScript to highlight column based on dropdown list selection

I have a data table with a dropdown box that sorts the table by column. I am trying to highlight the column that is selected/sorted by the dropdown. I am using the following code to obtain the index of the dropdown item:
<script>
var sel = document.getElementById('asorting').selectedIndex;
alert(sel);
</script>
I am using the following CSS code to highlight the column:
<style>
table td:nth-of-type(3)
{
background-color:#E0E0E0;
}
</style>
Both of these work on their own, but I am trying to update the "table td:nth-of-type(3)" to change based on the value of my sel variable. I have tried using (" + sel + ") to feed the variable to the CSS, but that is not working.
I am not very experienced in JS and have not been able to find anything on this site that relates exactly to what I am trying.
Any help would be greatly appreciated.
You can toggle classes in javascript by arriving at a logic like this
<html>
<head>
<script>
function changeStyle(v){
elements = document.getElementsByClassName('hightlight');
if(elements.length > 0){
for (let element of elements){
element.classList.remove('hightlight');
}
}
document.getElementById('data').children[parseInt(v)-1].className = "hightlight";
}
</script>
</head>
<body>
<style>
.hightlight {
color : red
}
</style>
<select id="asorting" onchange="changeStyle(this.value)">
<option class="row" value="1">one</option>
<option class="row" value="2">two</option>
<option class="row"value="3">three</option>
</select>
<table>
<tbody id="data">
<tr>
<td>one</td>
</tr>
<tr>
<td>two</td>
</tr>
<tr>
<td>three</td>
</tr>
</tbody>
</table>
</body>
</html>

How to give value from select box everytime increase button of dynamically Input Jquery

I am using jQuery dynamic table inputs in my form.Whenever i select country,i get the value from select box.But when i increase dynamic button (+) and again select the country from select box from another input field.i get same value of country from first selectbox field
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
button data-role="add">Add</button>- // button for increasing or decreasing input
</td>
</tr>
</tbody>
</table>
In script file.When I select country at first it will come value right in console.but when i increase input form then i select again another country then value of country will give same as first time selected.So how should i give value of country i selected everytime i increase dynamically input button
$(document).on(
'click',
'[data-role="dynamic-fields"],
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first- child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity()
}
);
$(document).on('change', " select[name='country[]']", function(){
updatecity();
});
function updatecity(){
$country = $(" select[name='country[]']").val();
console.log($country)
}
Currently, updatecity always gives you the value of the first result of $(" select[name='country[]']"). While the values of the other dropdown lists are ignored.
function updatecity(){
$country = $("select[name='country[]']").val();
console.log($country)
}
To make each dropdown list's call to updatecity behave with respect to its own value, you can add a parameter to updatecity to tell which country to update.
function updatecity($target){
$country = $target.val();
console.log($country);
}
Having the function signature changed, you will also need to update places where you call updatecity
$(document).on(
'click',
'[data-role="add"]',
function(e) {
// ...
updatecity($("select[name='country[]']"))
});
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
Also, the code you're showing will insert a new inline-form whenever <tbody> is clicked, so I changed the selector from [data-role="dynamic-fields"] to [data-role="add"]
As a sidenote, I notice that updatecity doesn't actually do anything except logging a value. You might want to have its behavior match its name.
Below I've attached a code snippet for demonstration.
$(document).on(
'click',
'[data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
updatecity($("select[name='country[]']"))
}
);
$(document).on('change', "select[name='country[]']", function(e){
updatecity($(this));
});
function updatecity($target){
$country = $target.val();
console.log($country)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="dynamic-fields-table">
<thead>
<tr>
<th >Country</th>
<th >City</th>
<th></th>
</tr>
</thead>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<select name="country[]" class="form-control">
<option value="1">USA</option>
<option value="2">Russia</option>
<option value="3">Japan</option>
</select>
</td>
<td>
<input type="text" name="city[]" class="form-control">
</td>
<td>
<button data-role="add">Add</button><!-- button for increasing or decreasing input-->
</td>
</tr>
</tbody>
</table>

Dynamically add rows and run the script

I have a table that's creating rows dynamically upon button click. This input box contains an auto suggest script. When , I am trying to perform an input on the the first box(the one that is default created) , the auto complete works fine. But, on performing the dynamic adding of the row, the script for that row doesn't work. How to invoke the auto complete script on the new ?
<html>
<body>
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr>
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
{!! Form::text('nameId', null,['class'=>'form-control auto', 'placeholder' => 'name']) !!}
</td>
</tr>
</body>
</table>
<script type="text/javascript">
$(document).ready(function ()
{
$("#add").click(function()
{
$('#tableAdd tr:last').after('<tr><td>{!! Form::text('project_manager_name', null,['class'=>'form-control pmID', 'placeholder' => 'Project Manager']) !!}</td></tr>')
});
});
$(".auto")
.on("keydown", keyDownEventForProjectAndCompetencyLead)
.autocomplete(
{
//function that autocompletes the input
});
</script>
</body>
</html>
Jquery sometimes has a little trouble identifying elements that have been programatically added to the DOM just by the original class / id. Try using a different selector method to check against the modified page:
$(document)
.on("keydown", ".auto", keyDownEventForProjectAndCompetencyLead)
.autocomplete( // etc )
Your selector isn't applying to DOM elements added after the page is loaded.
Modify as above to listen on all element in document that match, or attach listener on each new element created:
<html>
<body>
<button id="add">add</button>
<table id="cooltable">
<tr>
<td>cool table cell</td>
</tr>
</table>
<script type="text/javascript">
function autoPopulate(event){
// some code
event.currentTarget.value = "auto populated content";
}
let add_button = document.getElementById('add');
add_button.addEventListener('click',(event)=>{
let new_row = document.createElement('tr'); // create row
let new_cell = document.createElement('td'); // create cell
let new_input = document.createElement('input'); // create input
new_input.type = 'text';
new_input.value = "default content";
new_input.addEventListener('keydown', (event)=>{ // attach listener
autoPopulate(event);
});
new_cell.appendChild(new_input) // add input to cell
new_row.appendChild(new_cell) // add cell to row
document.getElementById('cooltable').appendChild(new_row); // add row to table
})
</script>
</body>
</html>
Problem here is you are adding callback on "keyDown" event which is not happening hence your script is not running
To fix this you should add eventlistener on jquery load()
Or you should using .bind('DOMNodeInserted DOMNodeRemoved') to call function when new node are added or deleted.
<div id='myParentDiv'> </div>
<button>Click </button>
$("button").click(function(){
$("#myParentDiv").append("<div class='test'></div>");
});
$("#myParentDiv").bind("DOMNodeInserted",function(){
alert("child is appended");
});
Here is working demo
https://jsfiddle.net/vickykumarui/28edcsmb/
Code for Table Example
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr id = "test1">
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
Test 1
</td>
</tr>
</body>
</table>
var numberOFRow = 1;
$("#add").click(function(){
numberOFRow++
$('#tableAdd tr:last').after('<tr id = test'+numberOFRow +'><td> Test' + numberOFRow + '</td></tr>')
});
$("#tableAdd").bind("DOMNodeInserted",function(){
alert("Row number"+ numberOFRow+ "created");
});
Working Demo for your table examplehttps://jsfiddle.net/vickykumarui/qpxL8k4c/

Jquery validation plugin rule

I need help in writing the jquery validation rule (i am using Jquery Validation Plugin) for following scenario.
Below is scenario...
Based on first dropdown value, second dropdown will be enabled. And we need to make selection from second dropdown and add it to table using Add button.
Validation rule should be like below.
If first dropdown selection enabled the second dropdown, but non of the value from second dropdown is added to table (i mean table is empty), then we need to show error message against second dropdown while hitting submit button in the form.
I tried adding attr like "data-rule-{addmethod_rulename}" to second dropdown and wrote custom addmethod rule using first dropdown value and table size, but it is not working.
JSP code:
<form ....>
:
:
:
<b:form-group label="${firstdropdown}" labelFor="firstdropdown" cssBody="col-sm-2" cssClass="required">
<form:select path="firstdropdown" name="firstdropdown" class="form-control" required="required">
<form:option value="" label=""/>
<form:options items="${firstdropdownvalues}"/> {This items has two values - One will disable below dropdown and another will enable}.
</form:select>
</b:form-group>
:
:
:
<b:form-group label="${seconddropdown}" labelFor="seconddropdown" cssBody="col-sm-4" cssClass="required">
<div class="form-inline">
<select name="seconddropdown" class="form-control" disabled>
<option value=""></option>
<c:forEach items="${values}" var="dropdown">
<option value="${dropdown.name}">${dropdown.name}</option> {This items will have several values - we can select one by one and add it to below table using this addsite button}.
</c:forEach>
</select>
<button id="addbtn" type="button" class="btn btn-primary" disabled><spring:message code="form.button.platform.addbtn"/></button>
</div>
</b:form-group>
:
:
:
<b:form-group cssBody="col-sm-6">
<table id="pfmtable" class="table table-striped table-bordered dt-responsive">
<thead>
<tr>
<th><input name="select_all" type="checkbox"/></th>
<th>Sites</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</b:form-group>
:
:
:
</form>
Javascript code:
jQuery.validator.addMethod("isadded", function(value, element) {
return $('#firstdropdown').val() == 'Enable_Value' && $("#pfmtabletr").length > 0;
}, "* Atleast one site should be selected");
$('button:submit').click(function(){
var name = $('#name').val();
var $form = $('form');
$form.validate({
rules:{
seconddropdown: {isadded: true}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},

Trouble cloning a set of selects dependent on each other

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.

Categories

Resources