This question is a follow-up to this question.
I've created this JSFiddle for demonstration purposes.
Note that when searching for a value in column1 the search works as expected. However when searching for a value in column2 (using the same "search field"), data_table.search does not appear to be called at all and relevant rows can not be found (press F12 to see debug info in the console).
var data_table = $("#table").DataTable();
var search_term = null;
$.fn.DataTable.ext.search.push(
function(settings, row, index) {
if (search_term) {
search_term = search_term.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
search_term = search_term.toLowerCase();
}
console.log(`search_term is ${search_term}`)
var approver = $(data_table.cell(`:eq(${index})`, ':eq(0)').node()).find('.approver-select').val().toLowerCase();
console.log(`approver is ${approver}`)
var approver_match = approver.match(search_term);
console.log(`approver_match is ${approver_match}`)
var network_or_group = $(data_table.cell(`:eq(${index})`, ':eq(1)').node()).find('.network-or-group-text').val().toLowerCase();
console.log(`network_or_group is ${network_or_group}`)
var network_or_group_match = network_or_group.match(search_term);
console.log(`network_or_group_match is ${network_or_group_match}`)
console.log(`approver_match || network_or_group_match || !search_term is ${approver_match || network_or_group_match || !search_term}`)
console.log('')
console.log('')
return approver_match || network_or_group_match || !search_term;
}
);
$('#table_filter input', data_table.table().container()).on('keyup.DT cut.DT paste.DT input.DT search.DT', event => {
search_term = $(event.target).val();
data_table.draw();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table id="table">
<thead>
<th>column1</th>
<th>column2</th>
</thead>
<tbody>
<tr>
<td>
<select class="approver-select">
<option selected>user1</option>
<option>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="1.1.1.1/32">
</td>
</tr>
<tr>
<td>
<select class="approver-select">
<option>user1</option>
<option selected>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="2.2.2.0/24">
</td>
</tr>
</tbody>
</table>
</body>
<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">
</html>
A simpler way of doing it using the html-input type is as below. You define the columns you're targeting and you're returning the value upon search. It works for both the select and the input.
You won't need to check for keyup.DT cut.DT paste.DT input.DT search.DT as datatables does that for you automatically as well.
$.fn.dataTableExt.ofnSearch['html-input'] = function(value) {
return $(value).val();
};
var data_table = $("#table").DataTable({
columnDefs: [{
"type": "html-input",
"targets": [0, 1]
}]
});
<html>
<body>
<table id="table">
<thead>
<th>column1</th>
<th>column2</th>
</thead>
<tbody>
<tr>
<td>
<select class="approver-select">
<option selected>user1</option>
<option>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="1.1.1.1/32">
</td>
</tr>
<tr>
<td>
<select class="approver-select">
<option>user1</option>
<option selected>user2</option>
</select>
</td>
<td>
<input class="network-or-group-text" type="text" value="2.2.2.0/24">
</td>
</tr>
</tbody>
</table>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.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">
</html>
This is cleaner and uses the basic type property of datatables rather than filtering all data upon search as you're doing right now.
Related
I have a dynamically generated table like below
this is the code that generate this table
function pullInventory(data) {
var container = document.getElementById('inventoryContainer')
var index = 0;
console.log(index)
data.forEach(function(awardsSnap) {
index ++;
// console.log(awardsSnap, index)
var awardItem = awardsSnap.val()
// Attach an asynchronous callback to rea
var NSNcard = `
<tr>
<td class="serial">${awardItem.NSN}</td>
<td> ${awardItem.Nomenclature} </td>
<td> ${awardItem.Awarddate} </td>
<td> ${awardItem.Awardid} </td>
<td>
<input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty${index}"style="width: 110px;">
</td>
<td>
<input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">
</td>
</tr>
`;
container.innerHTML += NSNcard;
});
}
I want to get all the user entered quantity and price on a button click so I use this
document.querySelector("#savebtn").addEventListener("click", e => {
var rows = document.getElementById("WelcomeTable").getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;
saveInventory(rows);
});
function saveInventory(rows) {
const columnHeader = Array.prototype.map.call(
document.querySelectorAll(".table th"),
th => {
return th.innerHTML;
}
);
const tableContent = Object.values(
document.querySelectorAll(".table tbody tr")
).map(tr => {
const tableRow = Object.values(tr.querySelectorAll("td")).reduce(
(accum, curr, i) => {
const obj = { ...accum };
obj[columnHeader[i]] = curr.innerHTML.trim();
console.log(accum, curr, i)
return obj;
},
{}
);
return tableRow;
});
}
everything works fine except that the two input column in the table above does not detect user input. I'm not able to get the quantity and price value entered.
Award Date: "08-23-2012"
Award#: "SP452013D0055"
NSN: "S222V00004789"
Nomenclature: " BATTERIES, NICKEL-CADMIUM"
Quantity: "<input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty18" style="width: 110px;">"
Unit-Price: "<input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">"
I tried this and other things but they output undefine
obj[columnHeader[4]]=curr.val();
obj[columnHeader[4]]=curr.value;
how could i get the enetered quantity and price from the dynamic table?
You could try doing something like this:
window.onload = ()=>{
let targetTable = document.getElementById('target-table');
let targetTableRows = targetTable.rows;
let tableHeaders = targetTableRows[0];
// start from the second row as the first one only contains the table's headers
for(let i = 1; i < targetTableRows.length; i++){
// loop over the contents of each row
for(let j = 0; j < targetTableRows[i].cells.length; j++){
// something we could use to identify a given item
let currColumn = tableHeaders.cells[j].innerHTML;
// the current <td> element
let currData = targetTableRows[i].cells[j];
// the input field in the row
let currDataInput = currData.querySelector('input');
// is the current <td> element containing an input field? print its value.
// Otherwise, print whatever is insside
currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`)
: console.log(`${currColumn}: ${currData.innerHTML}`);
}
}
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table" id="target-table">
<thead>
<tr>
<th scope="col">Person #</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
<td><input type="text" value="01-quantity" id="value-01"></td>
<td><input type="text" value="01-price" id="value-01-2"></td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
<td><input type="text" value="02-quantity" id="value-02"></td>
<td><input type="text" value="02-price" id="value-02-2"></td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
<td><input type="text" value="03-quantity" id="value-03"></td>
<td><input type="text" value="03-price" id="value-03-2"></td>
</tr>
</tbody>
</table>
What is done in the example above should also work for your specific case.
Also, here's a working exmaple :)
val() is jQuery method. You'll need to use .value in JavaScript.
obj[columnHeader[i]] = curr.innerHTML.trim();
innerHtml.trim returns only tag having direct child with text in it. In your code last two td having an input as child.
so in that case you need to check 'curr' having a child available. if there is a child available and its tagName is input, then you have to use childs value.
for example
obj[columnHeader[i]] = curr.children.length && curr.children[0].tagName=="INPUT" ? curr.children[0].value : curr.innerHTML.trim();
the above condition can be check and assign to a variable before it is assigned to key
My Requirment:
I have table with quantity cell as editable when change quantity it need to multiply with other parent td value.and sum the column values .
(i.e) if i change quantity to 2 then the parent rows need multiply by 2 & columns get value get added
I done all the calculation part the only thing when i delete or change the quantity the calculated value remain same how to revert back to old values
Here is my fiddle
Fiddle link
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
<!-- console.log(preVal); -->
if(preVal && preVal == val){
return;
}
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1){
return;
}
$(this).siblings().each(function(){
var tbvalue=$(this).text();
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
})
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i < 8; i++) {
var sum = 0;
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').each(function() {
sum += parseInt($(this).text()) || 0;
});
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>5</td>
<td>4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>8</td>
<td type>2</td>
<td>3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td>20</td>
<td>3</td>
<td>5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
Inside every row, with the td that store the numbers to be multiplied, keep the original numbers in a data-val attribute in the td, and multiply your content editable value with that. Display the multiplied value as the td text. One change here is that, when you delete the value of contenteditable cell, it takes it as 1 for row calculation, but does not consider it for column multiplication.
HTML part
<div class="container">
<h2>Table calculation</h2>
<p>Calculaton</p>
<table class="auto_sum table table-hover">
<thead>
<tr>
<th>value1</th>
<th>value2</th>
<th>value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td data-val="10">10</td>
<td data-val="5">5</td>
<td data-val="4">4</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="8">8</td>
<td data-val="2">2</td>
<td data-val="3">3</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr>
<td data-val="20">20</td>
<td data-val="3">3</td>
<td data-val="5">5</td>
<td class="quantity" type="number" contenteditable>1</td>
</tr>
<tr class="total">
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
JS Part
$(document).ready(function(){
$('.quantity').on('change, keyup',function(){
var val=$(this).text();
// To avoid auto inc while pressing arrow keys
var preVal =$(this).data('prevval');
$(this).data('prevval',val);
//To avoid auto inc while pressing arrow keys //
if(val =='' || isNaN(val) || val < 1 || val == undefined){
val = 1;
}
$(this).siblings().each(function(){
var tbvalue=$(this).data("val");
var result= parseInt(tbvalue)*parseInt(val);
$(this).text(result);
});
autoSum();
});
autoSum();
});
function autoSum(){
for (var i = 1; i <= 4; i++) {
var sum = 0;
var tdBoxes = $('.auto_sum>tbody>tr>td:nth-child(' + i + ')');
for(var j=0; j<tdBoxes.length-1;j++)
{
var value = $(tdBoxes[j]).text();
//alert(value);
sum += (value == undefined || value == "")? 0 : parseInt(value);
}
// set total in last cell of the column
$('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().html(sum);
// $('.auto_sum>tbody>tr>td:nth-child(' + i + ')').last().toggleClass('total');
}
}
All details are commented in working demo. I added <form>, <output>, <input type='number'> and <input type='hidden'>. Also I don't remember <td> having a type attribute or a value of number either.
With the combination of the right elements and attributes (and maybe even a little CSS), you don't have to write so much JS/jQ because there many aspects of form functions built within HTML.
Demo
// Reference the <form>
var main = document.forms.main;
// Reference of all of <input> and <output> of <form>
var field = main.elements;
/* Register the input event on the <form>
|| ANY input event triggered within <form> will...
*/
main.addEventListener('input', function(e) {
// Check to see which field is the user inputing into
if (e.target !== e.currentTarget) {
// Reference that field
var input = document.getElementById(e.target.id);
// console.log(input.value);
// Get the row of the field
var row = input.parentNode.parentNode;
// console.log(row);
/* Gather all hidden fields of that row into a NodeList
|| and convert that NodeList into an array.
*/
var rowArray = Array.from(row.querySelectorAll('[type=hidden]'));
// console.log(rowArray);
// On each hidden field, perform the following function...
rowArray.forEach(function(cel, idx) {
// Get the value of hidden field
const base = cel.value;
// Find the <output> that comes after the hidden field
var output = cel.nextElementSibling;
/* Calculate the product of the hidden field's value
|| and the input field's value
*/
var val = parseInt(base, 10) * parseInt(input.value, 10);
// Display the prouct in the <output>
output.value = val;
});
/* Because we registered the input event on the <form>,
|| we have many ways to manipulate the <form>'s fields.
|| In this demo we have been using:
|| HTMLFormElement and HTMLFormControlsCollection interfaces
|| https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement
|| http://www.dyn-web.com/tutorials/forms/references.php#dom0
*/
field.out1.value = Number(field.o1a.value) + Number(field.o1b.value) + Number(field.o1c.value);
field.out2.value = Number(field.o2a.value) + Number(field.o2b.value) + Number(field.o2c.value);
field.out3.value = Number(field.o3a.value) + Number(field.o3b.value) + Number(field.o3c.value);
field.out4.value = Number(field.out1.value) + Number(field.out2.value) + Number(field.out3.value);
}
});
.total {
background-color: #000;
color: #fff;
font-weight: bold;
}
input,
output {
display: inline-block;
font: inherit;
width: 6ch;
border: 0;
text-align: center;
}
.quantity input {
padding-top: .5em;
outline: 0;
}
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<form id='main'>
<table class="auto_sum table table-hover">
<thead>
<caption>
<h2>Table Calculation</h2>
<h3>Quanities</h3>
</caption>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id='rowA'>
<td>
<!--[0][1]-->
<input id='v1a' type='hidden' value='10'>
<output id='o1a'>0</output>
</td>
<td>
<!--[2][3]-->
<input id='v2a' type='hidden' value='5'>
<output id='o2a'>0</output>
</td>
<td>
<!--[4][5]-->
<input id='v3a' type='hidden' value='4'>
<output id='o3a'>0</output>
</td>
<td class="quantity">
<!--[6]-->
<input id='qa' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowB'>
<td>
<!--[7][8]-->
<input id='v1b' type='hidden' value='8'>
<output id='o1b'>0</output>
</td>
<td>
<!--[9][10]-->
<input id='v2b' type='hidden' value='2'>
<output id='o2b'>0</output>
</td>
<td>
<!--[11][12]-->
<input id='v3b' type='hidden' value='3'>
<output id='o3b'>0</output>
</td>
<td class="quantity">
<!--[13]-->
<input id='qb' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr id='rowC'>
<td>
<!--[14][15]-->
<input id='v1c' type='hidden' value='20'>
<output id='o1c'>0</output>
</td>
<td>
<!--[16][17]-->
<input id='v2c' type='hidden' value='3'>
<output id='o2c'>0</output>
</td>
<td>
<!--[18][19]-->
<input id='v3c' type='hidden' value='5'>
<output id='o3c'>0</output>
</td>
<td class="quantity">
<!--[20]-->
<input id='qc' type='number' value='0' max='999' min='0'>
</td>
</tr>
<tr class="total">
<td>
<!--[21]-->
<output id='out1' for='o1a o1b o1c'>0</output>
</td>
<td>
<!--[22]-->
<output id='out2' for='o2a o2b o2c'>0</output>
</td>
<td>
<!--[23]-->
<output id='out3' for='o3a o3b o3c'>0</output>
</td>
<td>
<!--[24]-->
<output id='out4' for='out1 out2 out3'>0</output>
</td>
</tr>
</tbody>
</table>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Trying to self create a validation that compares Gross and Tare values in the table using jQuery validation plugin. Tare should always be smaller than Gross.
Here is the JS code:
$.validator.addMethod('lessThan', function (value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({rules: {tare: {lessThan: ".gross"}}});
And my HTML:
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
</tbody>
</table>
</form>
This code works fine when only have one row involved.
When comes two table rows, it compares the 2nd row tare value with the 1st row gross value. Apparently I want it to compare 2nd row tare value with 2nd row gross value. Also for some reason the error message shows up at the 1st row.
Here is one screen shot:
Please advise how do I change my code to make it working properly.
And here is the CDN that I am using:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
Looking for $('.gross').val() will always retrieve the value of the first matched element (in the whole document).
Instead, look only in the row containing the element being validated:
var j = parseInt($(element).closest('tr').find(param).val());
$.validator.addMethod('lessThan', function(value, element, param) {
console.log(element);
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(element).closest('tr').find(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({
rules: {
tare: {
lessThan: ".gross"
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
</tbody>
</table>
</form>
I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.
Trying to take this table and take the names, when I click one radio button it changes the names from something like: Tom Hanks to Hanks, Tom. Here is the html:
<h1>Address Book</h1>
Show Names as:
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbod
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Interview Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise</td>
</tr>
</tbody>
</table>
</div>
Here is the jquery, its all I could come up with and does not work at all. :(
$(document).ready(function () {
$("input[name='change_last_first']").click(function () {
$(".name").text(function() {
$(this).split(" ").reverse();
});
});
});
});
You need to return the result. Also since you are using the function arg syntax of text use the second argument of the function for the current text.
$(".name").text(function(_, cur) {
return curText.split(/\s+|,/).reverse();
});
Fiddle
Another easy way to handle this assuming the general format of name is First Last or Last, First:
$("input[name='change_last_first']").change(function () {
var arr = [" ", ","],
sep = this.value === 'first' ? 0 : 1;
$(".name").text(function (_, curText) {
return curText.split(arr[sep % 2]).reverse().join(arr[(sep + 1) % 2]);
});
});
Demo
For this you need to split full name with space and than you can use reverse().
Note: because reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string.
$("input[name='change_last_first']").click(function () {
$(".name").each(function() {
var revName = $(this).text().split(" ").reverse().join(" ");
$(this).text(revName);
});
});
Try This