Disable and enable Select Value using Java Script - javascript

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>

Related

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>

Sorting Dynamic Table jQuery

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>
.

Error while input datepicker value into a html table

I try to make an input data into a table html. The other input works fine but I got error while I called the textbox that contains a datepicker value into my table. How to fix it? The error say's like this ("Object Html InputELement").
This is the code:­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
// JavaScript Document
function AddData() {
var x = document.getElementById("material").value;
var y = document.getElementById("kapal").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = "sadcsad";
var gender = $('input[name="gender"]').val();
var tgl = document.getElementById("datepicker").value;
var nopol = document.getElementById("nopol").value;
var netto = document.getElementById("netto").value;
rows += "<tr><td>" + datepicker + "</td><td>" + nopol + "</td><td>" + netto + "</td></tr>";
$(rows).appendTo("#table_bkk tbody");
}
}
function ResetForm() {
document.getElementById("person").reset();
}
<div id="kanan" class="btn btn-default" style="padding-left:20px" >
<table id="table_bkk" cellspacing='0' class="js-serial" border="2">
<thead>
<tr>
<th><center>No.</center></th>
<th><center>Tanggal</center></th>
<th><center>No.Polisi</center></th>
<th><center>Berat Material</center></th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td width="auto" style="border-right:hidden" align="right">Total Bongkaran</td>
<td width="auto" style="border-right:hidden" align="left">:</td>
<td width="auto" style="border-right:hidden">
<td width="auto">
<input type="text" id="sts" type="text" name="sensor1" maxlength="10" size=9 disabled="disabled"> </td>
</tr>
</table>
<script>
function incrementValue()
{
var value = parseInt(document.getElementById('no').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('no').value = value;
}
</script>

Want to get a specific child of a table row in JQuery

I have this table
<tbody>
<tr role="row" class="odd">
<td>
<input type="checkbox" id="checkBox0">
</td>
<td>
<img alt="image" class="img-rounded" src="" width="100" height="100">
</td>
<td>
Poporopos Act II
</td>
<td>
Ariba
</td>
<td>
12,00
</td>
<td>
<input id="quantity0" type="number" value="4" name="quantity" min="1" max="9999" size="4">
</td>
<td>
48,00
</td>
</tr>
I want to get both input type values (checkbox and number)in Jquery when the onchange event is triggered, it's worth saying that I use Jquery DataTables for render this and both inputs have the id "checkbox"+i and "quantity"+i where i is the number of the row rendered, and the inputs are a trick string types that are loaded in controller like this
public DataTablesResult<ShoppingCartHelper> GetShoppingCart(DataTablesParam dataTableParam)
{
List<ShoppingCart> query = db.ShoppingCart.ToList();
List<ShoppingCartHelper> newquery = new List<ShoppingCartHelper>();
ShoppingCart item;
decimal Total = 0;
for (int i = 0; i < query.Count; i++)
{
item = query.ElementAt(i);
ShoppingCartHelper helper = new ShoppingCartHelper();
helper.IdShoppingCart = item.IdShoppingCart;
helper.IdUser = item.IdUser;
SupplierMaterials sM = db.SupplierMaterials.FirstOrDefault(x => x.IdSupplierMaterials == item.IdSupplierMaterial);
string src;
if (sM.SupplierMaterialImages.Count == 0)
{
src = "<img alt = \"image\" class=\"img-rounded\" src=\"" + Url.Content("~/Images/box.png") + "\" width=\"100\" height=\"100\">";
}
else
{
DataBlobImage datablob = new DataBlobImage();
string path = sM.SupplierMaterialImages.FirstOrDefault().ImagePath;
int index = path.LastIndexOf('t') + 1;
string container = "environment"+path.Substring(index, path.Length - index);
Task<string> image = Task.Run(() => datablob.GetImage(path, container));
src = "<img alt = \"image\" class=\"img-rounded\" src=\"" + image.Result + "\" width=\"100\" height=\"100\">";
}
helper.supplierMaterialName = item.SupplierMaterials.Name;
helper.supplier = item.SupplierMaterials.Suppliers.SupplierName;
helper.supplierMaterial = src;
helper.quantity = "<input id=\"quantity" + i + "\" type = \"number\" value=\"" + item.Quantity + "\" name = \"quantity\" min = \"1\" max = \"9999\" size = \"4\"/>";
helper.Price = item.Price;
helper.IdCurrency = item.IdCurrency;
helper.Checked = "<input type=\"checkbox\" id=\"checkBox"+i+"\" />";
helper.subTotal = item.Price * item.Quantity;
helper.price = item.Price;
newquery.Add(helper);
}
return DataTablesResult.Create(newquery.AsQueryable(), dataTableParam,
uv => new
{
});
}
JavaScript
$(function () {
var table = $('#table-id').DataTable();
$('#table-id tbody').on('click', 'tr', function () {
alert("Check");
console.log(table.row(this).data());
});
});
hope this will help you, console complete checkbox in console and current status in console whenever state will change. Demo has more options
$(document).ready(function(){
$("input[type='checkbox']").on("change", function(){
console.log($(this).attr("id"));
if($(this).is(":checked")){
console.log("checked");
}
else{
console.log("not checked");
}
});
$("input[type='number']").on("change", function(){
console.log($(this).attr("id"));
});
});
Demo: https://jsfiddle.net/cx7aep1m/1/

Getting the table row values with jQuery

I am trying to get the values from an HTML table row. When I click on the table row delete button, I want to put those values on variables to send to the server. I have found something from here that looks like what I need, but when I put it together for my scenario, it does not work.
Here is the table HTML:
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
and here is the jQuery:
var tr = $('#thisTable').find('tr');
tr.bind('click', function(event) {
//var values = '';
// tr.removeClass('row-highlight');
var tds = $(this).addClass('row-highlight').find('td');
$.each(tds, function(index, item) {
values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
alert(values);
});
What am I doing wrong? I keep looking at examples but I cant seem to make this work.
Try this:
jQuery('.delbtn').on('click', function() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function(i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
});
DEMO
Give something like this a try:
$(document).ready(function(){
$("#thisTable tr").click(function(){
$(this).find("td").each(function(){
alert($(this).html());
});
});
});​
Here is a fiddle of the code in action: https://jsfiddle.net/YhZsW/
All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML I believe. I use the jQuery html function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>​
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});

Categories