Sorting Dynamic Table jQuery - javascript

Need help with sorting a table that I dynamically create with adding new rows with the Add Contact button. I managed to sort it by clicking on the column headers but I need to make it work with the HTML Tag. The table has index column, first name column, last name column, email, password, and phone column. I made the index to be random just so I don't need to input anything in the input fields and can try sorting the table with just adding new Contacts (rows) and sorting them by an index for start. I just need help sorting them by the index and populating the table. The rest I will figure it out. Any help will be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" media="screen" href="CSS/style.css" />
</head>
<body>
<div id="inputs-div">
<input type="text" placeholder="Your Name Sir" id="name-input">
<input type="text" placeholder="Your Last Name Sir" id="lastname-input">
<input type="text" placeholder="Your Email Sir" id="email-input">
<input type="password" placeholder="Your Password Sir" id="pass-input" >
<input type="text" placeholder="Your Phone Number" id="phone-input" >
<button id="new-row-btn">Add Contact</button>
</div>
<select class="custom-select" id="sort">
<option selected>Choose...</option>
<option value="1">Index</option>
<option value="2">First Name</option>
<option value="3">Last Name</option>
<option value="4">Email</option>
<option value="5">Phone Number</option>
</select>
<div>
<table id="my-table">
<thead>
<tr id="first-row">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Password</th>
<th>Phone</th>
<th>Sxxxy Action</th>
<th>Delete Action</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<script src="JS/jquery-3.2.1.js"></script>
<script src="JS/script.js"></script>
</body>
</html>
And here is the script
$(document).ready(function(){
let idCounter = parseFloat(Math.random() * 100).toFixed(0)
$('#new-row-btn').click(function(){
$("#my-table").append("<tr><td class='td-id'>"+ idCounter+"</td><td class='f_Name'>"+$("#name-input").val()+
"</td><td class='l_Name'>"+$("#lastname-input").val()+
"</td><td class='e_mail'>"+$("#email-input").val()+
"</td><td class='pass_in'>"+$("#pass-input").val()+
"</td><td class='phone_in'>"+$("#phone-input").val()+
"</td><td class='td-three-Btn'><button id='saveBtn"+idCounter+"' class='save-Btn'>save</button><button id='editBtn"+idCounter+"' class='edit-Btn'>edit</button><button id='delBtn"+idCounter+"' class='del-Btn'>del</button></td>"+ "<td class='td-del'><button class='del-row'>Del</button></td>"+ "</tr>")
$("#name-input").val("")
$("#lastname-input").val("")
$("#email-input").val("")
$("#pass-input").val("")
$("#phone-input").val("")
idCounter++;
$("td:even").css( "background-color", "#a35635" );
$("td:odd").css( "background-color", "#828e20" );
idCounter = parseFloat(Math.random() * 100).toFixed(0)
});
$(document).on('click', '.del-row', function (event) {
$(event.target).parent().parent().remove()
$("td:even").css( "background-color", "#a35635" );
$("td:odd").css( "background-color", "#828e20" );
});
$(document).on('click', '.edit-Btn', function (event) {
var $row = $(this).closest('tr');
var id = $row.find('.td-id').text();
var fName = $row.find('.f_Name').text();
var lName = $row.find('.l_Name').text();
var email = $row.find('.e_mail').text();
var pass = $row.find('.pass_in').text();
var phone = $row.find('.phone_in').text();
let choose_your_poison = "<td class='td-id'>"+ id +"</td><td class='f_Name'>"+"<input class='in_f_name' type='text' value='"+fName+"'>"+
"</td><td class='l_Name'>"+"<input class='in_l_name' type='text' value='"+lName+"'>"+
"</td><td class='e_mail'>"+"<input class='in_e_mail' type='text' value='"+email+"'>"+
"</td><td class='pass_in'>"+"<input class='in_pass_in' type='text' value='"+pass+"'>"+
"</td><td class='phone_in'>"+"<input class='in_phone_in' type='text' value='"+phone+"'>"+
"</td><td class='td-three-Btn'><button id='saveBtn"+idCounter+"' class='save-Btn'>save</button><button id='editBtn"+idCounter+"' class='edit-Btn'>edit</button><button id='delBtn"+idCounter+"' class='del-Btn'>del</button></td>"+ "<td class='td-del'><button class='del-row'>Del</button></td>"
$(this).closest('tr').html(choose_your_poison);
$("td:even").css( "background-color", "#a35635" );
$("td:odd").css( "background-color", "#828e20" );
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display','none');
del_btn.css('display','none');
save_btn.css('display','block');
});
$(document).on('click', '.save-Btn', function (event) {
var $row = $(this).closest('tr');
var f_Name = $row.find('.in_f_name').val();
var l_Name = $row.find('.in_l_name').val();
var e_Mail = $row.find('.in_e_mail').val();
var pass_W = $row.find('.in_pass_in').val();
var phone_N = $row.find('.in_phone_in').val();
$row.find('.f_Name').html(f_Name);
$row.find('.l_Name').html(l_Name);
$row.find('.e_mail').html(e_Mail);
$row.find('.pass_in').html(pass_W);
$row.find('.phone_in').html(phone_N);
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display','inline');
del_btn.css('display','inline');
save_btn.css('display','none');
});
//===================================================================
// Need Help
//===================================================================
$("#sort").on("change", function(event){
var pickedValue = event.target.value;
switch(pickedValue){
case '1': //sort by index
sortTable = (function(a, b){
var asc = order === 'asc',
tbody = table.find('tbody');
tbody.find('tr').sort(function(a, b) {
if (asc) {
return (parseInt($('td:first', a).text()) - parseInt($('td:first', b).text()));
}
else
{
return (parseInt($('td:first', b).text()) - parseInt($('td:first', a).text()));
}
}).appendTo(tbody);
})
break;
case '2': // sort by first name
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '3': // sort by last name
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '4': // sort by email date
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '5': // sort by phone
sortingFunction = (a, b) =>
(parseInt(a) - parseInt(b));
break;
default:
break;
}
sortTable($('#mytable'),'asc');
});
//===================================================================
// It works
//===================================================================
$('th').click(function(){
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
});

OK here is one possible solution using your existing column header for the sort, just trigger the click on the select choice (not sure why both exist but this does that). Note added the first row, cloned it and removed it - should make it easier to maintain than editing code.
I also took some liberty with classes, using CSS to style instead of script, using classes to target stuff etc.
Basically this manipulates the row in place on an edit. Two "delete" BUTTONS but I have no idea what the other is for so I used the delete row one.
This keeps the "id" in the table as data, increment from 0, not duplicating if rows removed.
$(document).ready(function() {
// get first row,clone it then remove it
var firstRow = $("#my-table")
.find('tbody')
.find('.contact-row')
.first().hide();
var cloneRow = firstRow.clone(true).data('last-row-counter', 0).show();
firstRow.remove();
$('#new-row-btn').on('click', function() {
// just use the table to keep track of rows added
let idCounter = $("#my-table").data('lastrowadded') + 1;
$("#my-table").data('lastrowadded', idCounter);
var newRow = cloneRow.clone(true);
newRow.find('.save-Btn').hide()
newRow.find('.td-id').html(idCounter);
newRow.find('.f_Name').html($("#name-input").val()); +
newRow.find('.l_Name').html($("#lastname-input").val());
newRow.find('.e_mail').html($("#email-input").val());
newRow.find('.pass_in').html($("#pass-input").val());
newRow.find('.phone_in').html($("#phone-input").val());
$("#my-table").find('tbody').append(newRow);
// blank out the onputs
$("#inputs-div").find(".contactfield").val("");
});
$('#my-table').on('click', '.del-row', function(event) {
$(this).closest('.contact-row').remove();
});
$('#my-table').on('click', '.edit-Btn', function(event) {
var $row = $(this).closest('.contact-row');
var edits = $row.find('.f_Name,.l_Name,.e_mail,.pass_in,.phone_in');
edits.each(function(index, element) {
var inp = $("<input class='editable' type='text'/>").val($(element).text());
$(element).html(inp);
});
$row.find('.edit-Btn').hide();
$row.find('.del-Btn').hide();
$row.find('.save-Btn').show();
});
$('#my-table').on('click', '.save-Btn', function(event) {
var $row = $(this).closest('tr.contact-row');
var edits = $row.find('.f_Name,.l_Name,.e_mail,.pass_in,.phone_in');
edits.each(function(index, element) {
var inp = $(element).find('input.editable');
$(element).html(inp.val());
});
$row.find('.edit-Btn').show();
$row.find('.del-Btn').show();
$row.find('.save-Btn').hide();
});
$("#sort").on("change", function(event) {
var pickedValue = event.target.value;
$('#my-table').find('.first-row').find('th').eq(pickedValue).trigger('click');
// console.log(pickedValue);
});
$('#my-table').on('click', 'th', function() {
var table = $(this).closest('table');
var rows = table.find('tr.contact-row')
.toArray()
.sort(comparer($(this).index()));
this.asc = !this.asc;
if (!this.asc) {
rows = rows.reverse();
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i]);
}
});
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index),
valB = getCellValue(b, index);
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
}
}
function getCellValue(row, index) {
return $(row).children('td').eq(index).text();
}
});
#my-table tbody tr.contact-row>td {
background-color: #a35635;
}
#my-table tbody tr.contact-row>td:nth-child(odd) {
background-color: #828e20;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="inputs-div">
<input class="contactfield" type="text" placeholder="Your Name Sir" id="name-input">
<input class="contactfield" type="text" placeholder="Your Last Name Sir" id="lastname-input">
<input class="contactfield" type="text" placeholder="Your Email Sir" id="email-input">
<input class="contactfield" type="password" placeholder="Your Password Sir" id="pass-input">
<input class="contactfield" type="text" placeholder="Your Phone Number" id="phone-input">
<button id="new-row-btn">Add Contact</button>
</div>
<div>
<select class="custom-select" id="sort">
<option selected>Choose...</option>
<option value="0">Index</option>
<option value="1">First Name</option>
<option value="2">Last Name</option>
<option value="3">Email</option>
<option value="5">Phone Number</option>
</select>
</div>
<div>
<table id="my-table" data-lastrowadded="0">
<thead>
<tr class="first-row">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Password</th>
<th>Phone</th>
<th>Sxxxy Action</th>
<th>Delete Action</th>
</tr>
</thead>
<tbody>
<tr class="contact-row">
<td class='td-id'>0</td>
<td class='f_Name'></td>
<td class='l_Name'></td>
<td class='e_mail'></td>
<td class='pass_in'></td>
<td class='phone_in'></td>
<td class='td-three-Btn'><button class='save-Btn'>save</button><button class='edit-Btn'>edit</button><button class='del-Btn'>del</button>
</td>
<td class='td-del'>
<button class='del-row'>Del Row</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>

This will do it even keeping your random numbers as id and sorting them accordingly.
Basically first you add a attr data-id to each tr. Then you hide all the tr rows. You loop through all the data-id and get the values (this being the id's) and put them in an array. Then you sort the array by either .sort which is ASC or .reverse as DESC. Change this value as needed. Then loop through the new sorted array arr and recreate the html by adding appending each new row according to sort order then display... BAM Done!
If you need to sort by other fields then you would change the class td-id of the td class you need
arr.push($(this).find('.td-id').text());
You just need to figure out how to let the code know which field it needs to sort by
$(document).ready(function() {
let idCounter = parseFloat(Math.random() * 100).toFixed(0)
var current;
$('#new-row-btn').click(function() {
current = '';
$("#my-table").append("<tr class='tr-id' data-id='" + idCounter + "'><td class='td-id'>" + idCounter + "</td><td class='f_Name'>" + $("#name-input").val() +
"</td><td class='l_Name'>" + $("#lastname-input").val() +
"</td><td class='e_mail'>" + $("#email-input").val() +
"</td><td class='pass_in'>" + $("#pass-input").val() +
"</td><td class='phone_in'>" + $("#phone-input").val() +
"</td><td class='td-three-Btn'><button id='saveBtn" + idCounter + "' class='save-Btn'>save</button><button id='editBtn" + idCounter + "' class='edit-Btn'>edit</button><button id='delBtn" + idCounter + "' class='del-Btn'>del</button></td>" + "<td class='td-del'><button class='del-row'>Del</button></td>" + "</tr>")
$("#name-input").val("")
$("#lastname-input").val("")
$("#email-input").val("")
$("#pass-input").val("")
$("#phone-input").val("")
idCounter++;
$("td:even").css("background-color", "#a35635");
$("td:odd").css("background-color", "#828e20");
idCounter = parseFloat(Math.random() * 100).toFixed(0)
$('.tr-id').hide();
var arr = [];
$('.tr-id').each(function() {
arr.push($(this).find('.td-id').text());
});
// if asc use .sort, if desc use .reverse
arr.sort(function(a, b) {
return a - b;
});
var i;
for (i = 0; i < arr.length; ++i) {
current += "<tr class='tr-id' data-id='" + arr[i] + "'>" + $('.tr-id[data-id="' + arr[i] + '"]').html() + "</tr>";
}
$('#tbody').html(current);
});
$(document).on('click', '.del-row', function(event) {
$(event.target).parent().parent().remove()
$("td:even").css("background-color", "#a35635");
$("td:odd").css("background-color", "#828e20");
});
$(document).on('click', '.edit-Btn', function(event) {
var $row = $(this).closest('tr');
var id = $row.find('.td-id').text();
var fName = $row.find('.f_Name').text();
var lName = $row.find('.l_Name').text();
var email = $row.find('.e_mail').text();
var pass = $row.find('.pass_in').text();
var phone = $row.find('.phone_in').text();
let choose_your_poison = "<td class='td-id'>" + id + "</td><td class='f_Name'>" + "<input class='in_f_name' type='text' value='" + fName + "'>" +
"</td><td class='l_Name'>" + "<input class='in_l_name' type='text' value='" + lName + "'>" +
"</td><td class='e_mail'>" + "<input class='in_e_mail' type='text' value='" + email + "'>" +
"</td><td class='pass_in'>" + "<input class='in_pass_in' type='text' value='" + pass + "'>" +
"</td><td class='phone_in'>" + "<input class='in_phone_in' type='text' value='" + phone + "'>" +
"</td><td class='td-three-Btn'><button id='saveBtn" + idCounter + "' class='save-Btn'>save</button><button id='editBtn" + idCounter + "' class='edit-Btn'>edit</button><button id='delBtn" + idCounter + "' class='del-Btn'>del</button></td>" + "<td class='td-del'><button class='del-row'>Del</button></td>"
$(this).closest('tr').html(choose_your_poison);
$("td:even").css("background-color", "#a35635");
$("td:odd").css("background-color", "#828e20");
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display', 'none');
del_btn.css('display', 'none');
save_btn.css('display', 'block');
});
$(document).on('click', '.save-Btn', function(event) {
var $row = $(this).closest('tr');
var f_Name = $row.find('.in_f_name').val();
var l_Name = $row.find('.in_l_name').val();
var e_Mail = $row.find('.in_e_mail').val();
var pass_W = $row.find('.in_pass_in').val();
var phone_N = $row.find('.in_phone_in').val();
$row.find('.f_Name').html(f_Name);
$row.find('.l_Name').html(l_Name);
$row.find('.e_mail').html(e_Mail);
$row.find('.pass_in').html(pass_W);
$row.find('.phone_in').html(phone_N);
let edit = $row.find('.edit-Btn')
let del_btn = $row.find('.del-Btn')
let save_btn = $row.find('.save-Btn')
edit.css('display', 'inline');
del_btn.css('display', 'inline');
save_btn.css('display', 'none');
});
//===================================================================
// Need Help
//===================================================================
$(document).on("change", "#sort", function(event) {
var pickedValue = event.target.value;
switch (pickedValue) {
case '1': //sort by index
sortTable = (function(a, b) {
var asc = order === 'asc',
tbody = table.find('tbody');
tbody.find('tr').sort(function(a, b) {
if (asc) {
return (parseInt($('td:first', a).text()) - parseInt($('td:first', b).text()));
} else {
return (parseInt($('td:first', b).text()) - parseInt($('td:first', a).text()));
}
}).appendTo(tbody);
})
break;
case '2': // sort by first name
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '3': // sort by last name
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '4': // sort by email date
sortingFunction = (a, b) =>
(a.localeCompare(b));
break;
case '5': // sort by phone
sortingFunction = (a, b) =>
(parseInt(a) - parseInt(b));
break;
default:
break;
}
sortTable($('#mytable'), 'asc');
});
//===================================================================
// It works
//===================================================================
$('th').click(function() {
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc) {
rows = rows.reverse()
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index),
valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index) {
return $(row).children('td').eq(index).text()
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" media="screen" href="CSS/style.css" />
</head>
<body>
<div id="inputs-div">
<input type="text" placeholder="Your Name Sir" id="name-input">
<input type="text" placeholder="Your Last Name Sir" id="lastname-input">
<input type="text" placeholder="Your Email Sir" id="email-input">
<input type="password" placeholder="Your Password Sir" id="pass-input">
<input type="text" placeholder="Your Phone Number" id="phone-input">
<button id="new-row-btn">Add Contact</button>
</div>
<select class="custom-select" id="sort">
<option selected>Choose...</option>
<option value="1">Index</option>
<option value="2">First Name</option>
<option value="3">Last Name</option>
<option value="4">Email</option>
<option value="5">Phone Number</option>
</select>
<div>
<table id="my-table">
<thead>
<tr id="first-row">
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Password</th>
<th>Phone</th>
<th>Sxxxy Action</th>
<th>Delete Action</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
<script src="JS/jquery-3.2.1.js"></script>
<script src="JS/script.js"></script>
</body>
</html>
.

Related

Disable and enable Select Value using Java Script

I am using below code.If i click Testing 1 or Testing 2 or selectAll,new rows will be created.I need to disable DatatType and Expected set value column if Execution Type is Get.If I select Set from Execution Type, DataType and Expected set value column should be enabled.How to implmente this? I am using this code in Html.erb file.How to create separate js method?
https://jsfiddle.net/bx5fa2vu/
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel=$("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
You can do it like this. Note that initially the fields are not disabled because no value is selected at the Execution Type select field. Maybe you want to make this more clear by adding an initial option with the text "Select Type" to the select field like you have it for the select for Data Type.
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel = $("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
$(document).on("change", ".ExeType", function() {
let type = $(this).val();
if (type === "getData") {
$(this).closest("tr").find(".parameterDscription").attr("disabled", "disabled");
$(this).closest("tr").find(".expectedValue").attr("disabled", "disabled");
} else {
$(this).closest("tr").find(".parameterDscription").removeAttr("disabled");
$(this).closest("tr").find(".expectedValue").removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="paramTable">
<tr>
<td><input type="checkbox" id="all" /></td>
<td>Select all</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 1</td>
<td>1.2.3.4.5</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 2</td>
<td>.1.3.4.5.8</td>
</tr>
</table>
<div class="tab-content">
<div id="protocol" class="tab-pane fade in active">
<div class="span3 border-0" style="overflow: scroll">
<table id="addParamTable" class="table table-bordered">
<thead>
<tr class="info">
<th>Excution Type</th>
<th>Parameter Name</th>
<th>Data Type</th>
<th>Expected Set Value</th>
</tr>
</thead>
<tbody class="parameter_table">
</tbody>
</table>
</div>
</div>
</div>

How can i multiply or add the values of a dynamic javascript input field

The input field are been generated by javascript. I want to pick each value no matter how many input field I generate...so I can use the values for some calculations.
<form action="{{ route('addmorePost') }}" method="POST">
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered">
<thead>
<tr>
<th width="55%">Sales Representative</th>
<th width="15%">Target per day</th>
<th width="15%">Monthly day</th>
<th width="10%"> + </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="target[]" class="form-control target" id="target" oninput="calc()">
</td>
<td><span id="sum1" onchange="add()">0</span> </td>
<td> - </td>
</tr>
</tbody>
<tfoot>
<tr>
<th>
</th>
<th> Total</th>
<th><span id="sumx">0</span> </th>
</tr>
</tfoot>
<script>
function add() {
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
</table>
</button>
</form>
BELOW IS THE JAVASCRIPT FOR GENERATED INPUT FIELDS
<script type="text/javascript">
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow();
});
function addRow(){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target2" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result1">0</span> </td>'+
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
THIS IS THE CODEI HAVE TRIED TO GET THE VALUES , MULTIPLY THEM BY 26 AND DISPLAY THE ANSWER ON sum1
<script>
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result1').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
PLEASE HELP!!!...WHAT AM I DOING WRONG
From your code every time you call addRow() the ID is always target2.
To auto change the ID, have a variable that holds the current ID and concatenate the string, you can make use of the var i.
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow(i);
});
function addRow(i){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target' + i + '" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result' + i + '">0</span> </td>'+ //This is modified to attach the current index to result
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
The i variable should always hold the index for the last row added
To multiply the values you have to make use of the same i variable, the function calc() should look like this, i suggest you rename i to something descriptive:
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
for(var j = 1; j <= i; j++) {
var value2 = document.getElementById('target' + j).value;
document.getElementById('result' + j).innerHTML = parseInt(value2 * 26); // This is to target the result span that corresponds to the input value
}
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
Thank u..i was able to do it this way...after i increate the value of the id like this
id="target' + i + '" and also span
so i use the below code to get the values manually...not the best option, but it solved my problem cos i dont need more than three input fields
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result2').innerHTML = parseInt(value2 * 26);
document.getElementById("products").disabled = false;
var value2 = document.getElementById('target3').value;
document.getElementById('result3').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML || 0;
var valuey = document.getElementById('result2').innerHTML || 0;
var valuenew = document.getElementById('result3').innerHTML || 0;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey) + parseInt(valuenew);
}
</script>

how to get array values, on input field

So I have multiple table data insert I want to get input value on some field so I can calculate on another field. How can I do that if that is an array field?
I've tried using javascript but it's only working on first field (not array field).
function tot() {
var txtFirstNumberValue = document.getElementById('price').value;
var txtSecondNumberValue = document.getElementById('qty').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>"
"<input id='price' type='text' name='price[]' onkeyup='tot();' required>"
"<input id='qty' type='text' name='qty[]' onkeyup='tot();' required>"
"<input type='text' name='total[]' required>"
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br><input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot();" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot();" required>
<input id="total" type="text" name="total[]" required>
<div id="insert-form"></div>
I expect that way works on added array table but it's not, it only affects field on my first table.
You can not assign the same ID to multiple DOM elements on the same page. I have updated your code a bit to use the item number with the ID. Like, for item 1 ID is price, for item 2 ID is price-2, for item 3 ID is price-3 and so on. Same done with qty and total.
You may try this code:
function sum_total() {
var totalSum = 0;
var calcTotalSum = document.getElementsByClassName("calc-total");
var totalItems = calcTotalSum.length;
var i = 0;
while(i < totalItems) {
if (calcTotalSum[i].value !== "") {
totalSum = totalSum + parseInt(calcTotalSum[i].value);
}
i += 1;
}
if(totalSum > 0) {
console.log("Total Sum is: ", totalSum);
}
}
function tot(event) {
var itemNo = event.target.getAttribute("data-item");
var txtFirstNumberValue = "";
var txtSecondNumberValue = "";
if (itemNo) {
txtFirstNumberValue = document.getElementById('price-' + itemNo).value;
txtSecondNumberValue = document.getElementById('qty-' + itemNo).value;
} else {
txtFirstNumberValue = document.getElementById('price').value;
txtSecondNumberValue = document.getElementById('qty').value;
}
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
if (itemNo) {
document.getElementById('total-' + itemNo).value = result;
} else {
document.getElementById('total').value = result;
}
}
sum_total();
}
$(document).ready(function(){
$("#btn-add-form").click(function(){
var addi = parseInt($("#addi-form").val());
var nextform = addi + 1;
$("#insert-form").append("<b>Item Price " + nextform + " :</b>" +
"<input type='text' name='names[]' required>" +
"<input id='price-" + nextform + "' data-item='" + nextform + "' type='text' name='price[]' onkeyup='tot(event);' required>" +
"<input id='qty-" + nextform + "' data-item='" + nextform + "' type='text' name='qty[]' onkeyup='tot(event);' required>" +
"<input id='total-" + nextform + "' class='calc-total' type='text' name='total[]' required>"
);
$("#addi-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#addi-form").val("1");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btn-add-form">Add</button>
<button type="button" id="btn-reset-form">Reset</button><br>
<input type="hidden" name="addi-form" id="addi-form" value=1 required>
<input type="text" name="names[]" required>
<input id="price" type="text" name="price[]" onkeyup="tot(event);" required>
<input id="qty" type="text" name="qty[]" onkeyup="tot(event);" required>
<input id="total" class="calc-total" type="text" name="total[]" required>
<div id="insert-form"></div>
Hope, it helps you.
EDITED: sum_total function to calculate the sum of the total amount.
I presume that you want to trigger the tot() function on the newly added table rows. For that purpose you need to:
call tot() function to bind to the newly added elements after they have been appended. Or use the jQuery bind method.
Use .class in place of #id attributes on the elemnts so that you can iterate through all of them using the class selector

Create array from Dynamic table

How can I create an array from this table/form? The onclick function formData() from the dynamic table only returns a concatenated string. I need to create an associative array in JSON using the 'device' variable as key, however I'll settle for any sort of array at all. Clearly, I'm not very good at this...
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementById("form");
//var device = document.getElementById('device').value;
//var j;
var obj = [];
for(j=0; j< cellData.length; j++)
{
obj += cellData[j].value;
}
var json = JSON.stringify(obj);
alert (json);
//document.getElementById('result').innerHTML = json;
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>
1) This my answer how do this on VueJS and jQuery
2) Vanilla js - CODEPEN - DEMO
// Get DOM elements
const $el = [
'#tmpl',
'#user-count',
'#people-count',
'#form-items',
'#btn-add',
'#form',
].reduce((res, item) => {
const method = item.startsWith('#')
? 'querySelector'
: 'querySelectorAll'
const key = item
.replace(/\W/ig, ' ').trim()
.replace(/\s+\w/g, v => v.trim().toUpperCase())
res[key] = document[method](item)
return res
}, {})
// Variable for dynamic template
const tmpl = $el.tmpl.innerHTML.trim()
// Click on Add new button
$el.btnAdd.addEventListener('click', () => {
const peopleCount = +$el.peopleCount.value
const html = Array(peopleCount)
.fill(tmpl)
.join('')
$el.formItems.insertAdjacentHTML('beforeend', html)
})
// Submit form
$el.form.addEventListener('submit', e => {
e.preventDefault()
alert('Submit form by ajax or remove this method for default behavior')
})
// Add form click (it's need for dynamic handler on child elements)
$el.form.addEventListener('click', e => {
// Delete behaviors
if (e.target.classList.contains('btn-del') && confirm('Are you sure?')) {
e.target.closest('.row').remove()
}
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
I have edited your code,
function createInputTable()
{
var num_rows = document.getElementById('rows').value;
var tableName = document.getElementById('conn_input_device').value;
var column_number = 2;
var tdefine = '<form id="form"><table id="table" border = "1">\n';
var theader = '<tr><th>No</th><th>Input</th><th>Output</th></tr>\n';
var caption = '<caption><input id="device" value ="' + tableName + '" /></caption>';
var tbody = '';
var tfooter = '</table>';
var createNewDevice = '<button onclick="formData();">Form Data</button></form>'
var i = 0;
for (var i= 0; i < num_rows; i++)
{
tbody += '<tr><td>' + (i+1) + '</td><td><input class="cell" id="i'+ i + '" type = "text"/></td>';
tbody += '<td><input class="cell" id="o'+ i + '" type="text"/></td></tr>\n';
}
document.getElementById('wrapper').innerHTML = caption + tdefine + theader + tbody + tfooter + createNewDevice;
}
function formData()
{
var cellData = document.getElementsByTagName("tr");
var obj = [];
for(var i=0;i<cellData.length-1;i++){
obj.push(document.getElementById("i"+i).value);
obj.push(document.getElementById("o"+i).value);
}
alert(JSON.stringify(obj));
}
<form id="tableGen" name="table_gen">
<label>Connecting device: <input type = "text" name = "conn_input_device" id = "conn_input_device"/></label><br />
<label>Number of inputs: <input type="text" name="rows" id="rows"/></label><br />
<input name="generate" type="button" value="Create Input Table!" onclick='createInputTable();'/>
</form>
<div id="wrapper"></div>

Why am i getting NaN while multipling select data-attrib with input value

I am having issues to get total for my <span class="cubics"></span>. I am getting NaN as my result when i input value to my <input class="item_unit" value=""> and multiply with select data-cubics
Here is my code
PHP To populate select options
foreach($result as $row)
{
$output .= '<option value="'.$row["unit_name"].'" data-cubics="'.$row["unit_price"].'" >'.$row["unit_name"].'</option>';
}
TABLE to display results
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Quantity</th>
<th>Select Unit</th>
<th>Total</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<tr class="bg">
<td width="33%">TOTAL</td>
<td width="33%"><span id="totalquantity"></span>
</td>
<td width="33%">TOTAL</td>
<td width="33%"><span class="totalcubics"></span>
</td>
</tr>
JAVASCRIPT To handle functionality
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><select name="item_unit[]" class="item_unit form-control"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><input class="qty form-control" type="text" value="0"/></td>';
html += '<td width="33%"><span class="cubics"></span>';
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);
$summands = $form.find('input.qty'); //*************** add this line
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.qty').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
});
});
function total() {
var total1 = 0;
$('span.cubics').each(function () {
var n = parseFloat($(this).text());
total1 += isNaN(n) ? 0 : n;
});
$('.totalcubics').text(total1.toFixed(2));
}
$(document).on('keyup' , 'input.qty' , function () {
var val = parseFloat($(this).val());
val = (val ? val * $(this).data('cubics') : '');
$(this).closest('td').next().find('span.cubics').text(val);
total();
});
var $form = $('#insert_form'),
$summands = $form.find('input.qty'),
$sumDisplay = $('span#totalquantity');
$form.keyup(function () {
var sum = 0;
$summands.each(function () {
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.text(sum);
});
$('input').on({
focus: function () {
if (this.value == '0') this.value = '';
},
blur: function () {
if (this.value === '') this.value = '0';
}
});
$(function() {
$('.qty').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.qty')
var mul = parseInt($(m[0]).val()).toFixed(2)
var res = p.find('.qty')
res.html(mul);
var total = 0;
$('.qty').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('.cubics').html(parseInt(total).toFixed(2));
});
});
$('.item_unit').change(calcVal);
function calcVal() {
$(".cubics").html($(this).children(':checked').data('cubics') * $('input.qty').text().trim())
}
// call on document load
calcVal();
</script>
Sorry couldn't narrow it down to the culprit lines. html += '<td width="33%"><span class="cubics"></span>'; is getting NaN as result
SELECT OPTIONS generated by PHP
<td><select name="item_unit[]" class="item_unit form-control">
<option value="">Select Unit</option>
<option value="Bags" data-cubics="40000" >Bags</option>
<option value="Bottles" data-cubics="20000" >Bottles</option>
<option value="Box" data-cubics="30000" >Box</option>
<option value="Dozens" data-cubics="90000" >Dozens</option>
</select></td>

Categories