To create jquery datepicker, we use the following function
$( function() {
$( "#datepicker" ).datepicker();
} );
<input type="text" id="datepicker">
I am trying to achieve a in-line editing functionality with a new record function as below
function createRowForAdd(){
var tRow = "<tr>"
for(var i = 0; i < array.length; i++){
var jsonObj = array[i];
tRow +="<td><input type='text' id='"+jsonObj.id+"' /></td>"
}
tRow += "</tr>";
return tRow;
}
function Add(){
var tRow = createRowForAdd();
$("#tblId tbody").append(tRow);
}
<button id="btnAdd" onclick="javascript:Add()">New</button>
<table id="tblId" border="1">
<thead>
<tr>
<th>Name</th>
<th>Birth Date</th>
<th>Joining Date</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
One or more columns may contain a date field. For those column(s), I would like to show a date picker. As I understand, document.ready function gets triggered once the DOM is ready. Is it possible to initiate a date picker on row add?
.datepicker() function just needs that the element is in the DOM, so you can execute it after you add the row without problems, applying your desired selector for that input fields.
About the selector, considering that you're going to have multiple datapicker inputs, avoid using the same id (id's are designed to be unique in the DOM). You better use a class instead.
function Add() {
var tRow = createRowForAdd();
$("#tblId tbody").append(tRow);
// When creating the row, set class="datepicker" the inputs of the row that
// has to be converted to a datetime picker. Then you just have to do this...
$("input.datepicker").datepicker();
}
Or even better, apply it only to the inputs from the new added row (the last one)...
function Add() {
$("#tblId tbody").append(createRowForAdd()).find('tr:last input.datepicker').datepicker();
}
EDITED: I can't see the value of your array variable, but looking at your code it looks like all the inputs of the same column will have the same id. As I mention earlier, avoid that because id's are designed to be unique in the DOM. If you need an id, you can use the row number to change the input for every id. Here you have an example with that idea...
HTML:
<button id="btnAdd">New</button>
<table id="tblId" border="1">
<thead>
<tr>
<th>Name</th>
<th>Birth Date</th>
<th>Joining Date</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQUERY:
// I'm making up the content of this array. The question doesn't show it.
var array = [
{ 'id': 'name', 'class': '' },
{ 'id': 'birthdate', 'class': 'datepicker' },
{ 'id': 'joiningdate', 'class': 'datepicker' },
{ 'id': 'something', 'class': '' }
];
function createRowForAdd(rowPos) {
var tRow = [];
for (var i=0, l=array.length; i<l; i++)
tRow.push('<td><input type="text" id="'+array[i].id+rowPos+'" class="'+array[i].class+'" /></td>');
return '<tr>' + tRow.join('') + '</tr>';
}
$('button#btnAdd').click(function() {
var rowPos = $("table#tblId tbody tr").length;
$("table#tblId tbody").append(createRowForAdd(rowPos)).find('tr:last input.datepicker').datepicker();
});
And the fiddle... https://fiddle.jshell.net/rigobauer/tpxnvpy4/
I hope it helps
Related
In my code below, when i select a checkbox it displays the name of the item checked. But my problem now is, the table is paginated so when i move to the next page and return, the already checked item goes back unchecked.
The same applies when i check a box and filter using the ajax request, when i return the already checked box will have moved to unchecked state.
How do i hide the table page to resolve this issue?
HTML
<table class="table" id="table" style="background-color:white" >
<thead>
<tr>
<th></th>
<th colspan="5"></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td><input onclick="return results(this)" data-item="{{$item->toJson()}}" type="checkbox" id="{!! $item->id !!}" name="{!! $item->name !!}" value="{!! $item->price !!}" /> </td>
<td>{{$item->name }}</td>
</tr>
#endforeach
</tbody>
</table>
{{$items->links()}}
JS
function results(item){
var major = JSON.parse(item.dataset.item);
if(item.checked == true) {
$('.panel').append(
'<div class="container "> '+
'<table style="width:100%;" class="table" id="tables">'+
'<thead>'+'<thead>'+
'<tbody>'+
'<tr>'+ '<td class="name" >'+major.name+'</td>'+] '</tr>'+
'</tbody>'+'</table>'+'</div>')}
} else {
});
}
}
}
AJAX
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
table.html("");
$.each(data, function(idx, elem){
table.append(
"<tr><td><input type='checkbox' onclick='return results(this)' data-item='"+JSON.stringify(elem)+"' id='"+elem.id+"' name='"+elem.name+"' value='"+elem.price+"' data-id="+elem.id+" /></td><td >"+elem.name+"</td><tr>"
);
});
}
Saving state is possible via "JavaScript - localStorage" functionality.
Today browsers have capability to save information that is more "cleaner" and informative then cookies.
On "checkbox" element I would add event listener that would start function called "saveState()". In this function I would save information about checkbox.
function saveState()
{
localStorage.setItem("checkBoxStatus", "Checked");
}
This information is saved into browser`s storage and won't be deleted until you delete it yourself.
To delete it you have two options:
`localStorage.removeItem("checkBoxStatus");`
`localStorage.clear();`
Then when you re-enter that page again, while you are "constructing" view you can add small function that will set state equal to the "saved" one.
function resumeState()
{
if(localStorage.getItem("checkBoxStatus") === "Checked)
//get check box and check or uncheck
}
HOW STORED DATA CAN BE USED
It's my point of view but I prefer building my HTML views via JavaScript, as I find it more cleaner way and easier also, because today you have frequent communication with "JavaScript/Ajax" functions and need more responsiveness.
so I would build my entire view with JavaScript Dom
**
function buildView()
{
var element = document.createElement("div");
var checkBox = document.createElement("input");
checkBox.settAttribute("type", "checkbox");
//here we will check
localStorage.getItem("checkBoxStatus") === "Checked" ? checkBox.setAttribute("checked", "true") : checkBox.setAttribute("checked", false);
element.appendChild(checkBox);
document.body.appendChild(element);
}
**
or use setTimeout function and stick to "HTML" views:
<body onload='setTimeout(buildView(), 2000);>'
this will wait until all the views are constructed and start after it.
You can set correct timing depending on how much data you are loading during "onload" event. If it's small data you can even wait for 1 second -> 1000
function buildView()
{
var checkBox = document.getElementById("checkBox");
//here we will check
if(localStorage.getItem("checkBoxStatus") === "Checked")
{
checkBox.setAttribute("checked", "true");
}
else
{
checkBox.setAttribute("checked", false);
}
}
Remember that main here is to use localStorage functionality to save data and after that how you will use that data, totally depends on developers imagination and creativity
I made a fiddle for you so that you can improve it in the way that you can use it for your purpose,here is the fiddle and the code:
HTML:
<div class="checkbox-set">
</div>
<div id = "result">
</div>
Js:
var id = "";
for(i=1 ; i<8 ;i++){
id="checkbox_"+i;
$('.checkbox-set').append('<input type="checkbox" id="'+ id +'" value="Click on me"/> <label for="'+id+'">Click on me</label> <br/> ');
}
var selected = [];
if(sessionStorage.selected) {
// selected = sessionStorage.selected;
var checkedIds= sessionStorage.selected.split(",");
$.each(checkedIds,function(i){
$("#" + checkedIds[i]).prop('checked', true);
selected.push(checkedIds[i]);
});
}
$('input[type="checkbox"]').change(function() {
if(this.checked) {
$(this).each(function(){
selected.push($(this).attr('id'));
//$("#result").html(selected);
});
}
if(!this.checked) {
const index = selected.indexOf($(this).attr('id'));
var tt= selected.splice(index, 1);
//$("#result").html(selected);
}
sessionStorage.selected = selected;
$("#result").html(sessionStorage.selected);
})
please confirm if it is helpful
I'm fairly new to coding. I have a jQuery datatable, and when I select a row, the tds of that row fill out html textboxes above the table. I'm trying to make it so whatever is entered into those textboxes (and upon pressing the save button), is then saved into the row.
Currently I have it so it saves 1 field/td. If I press on column 0, fill out the Name textbox and press save, it saves. But it works on any column. It should only be editing the correct td. Plus I want to edit the entire row, not just one td. I'm not sure how to accomplish this. Thanks for any help!
JSFiddle
Javascript:
var table = $('#example').DataTable();
(function () {
var table = document.querySelector('#example');
var name = document.querySelector('#nameinput');
var format = document.querySelector('#formatinput');
var address = document.querySelector('#addressinput');
var report = document.querySelector('#reportinput');
var alarm = document.querySelector('#alarminput');
table.addEventListener('click', onTableClick);
function onTableClick (e) {
var tr = e.target.parentElement;
var data = [];
for (var td of tr.children) {
data.push(td.innerHTML);
}
name.value = data[0];
address.value = data[1];
format.value = data[2];
report.value = data[3];
alarm.value = data[4];
console.log(alarm.value);
}
$("#saverow").click(function() {
var table1 = $('#data-table').DataTable();
var data = [];
data[0] = name.value;
data[4] = alarm.value;
console.log(name.value);
console.log(alarm.value);
table1.draw(true);
});
})();`
I've updated my code with what I've tried so far. Currently, what I type in the textboxes, correctly is displayed in the console (upon hitting the saverow button), now I cant figure out how to save that into the table.
i think it is mor responsive to edit data right in the table.
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Format</th>
<th>Report Time</th>
<th>Alarms</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>Tiger#gmail.com</td>
<td>email</td>
<td>1PM</td>
<td>Master</td>
<td class="td-button"></td>
</tr>
<tr>
<td>Bill Gates</td>
<td>111-111-1111</td>
<td>sms</td>
<td></td>
<td>Master</td>
<td class="td-button"></td>
</tr>
</tbody>
</table>
JS:
var table = $('#example').DataTable();
$("#example tbody tr").click(function(){
if (! $(this).find("button").length)
{
$(this).find("td").each(function(){
if (!$(this).hasClass("td-button"))
{
var text = $(this).text();
$(this).html ('<input type="text" value="' + text + '">')
} else
$(this).html ('<button class="button-save">Save</button>')
})
}
})
$(document).on("click", ".button-save",function(){
var tr = $(this).parent().parent();
tr.find("td").each(function(){
if (!$(this).hasClass("td-button"))
{
var text = $(this).find("input").val();
$(this).text(text)
} else
$(this).html('');
})
})
https://jsfiddle.net/91wvw619/
Am working on the table, my aim is to display rows orderly based on its sum of columns. I mean, highest valued rows should be displayed first and then, second highest values, then, go on.. Have tried and could not make it. Just give me an idea, and that is good enough for me. Am not able to come to any idea on how to reshuffle the rows based on its sum values. Any idea on this?
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" value="All" onclick="Turnthis();"/>All
<input type="radio" value="Top15" onclick="TurnOutthis();"/>Top5
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
</table>
</div>
After I pressed the 'Top5' button, then, the table should be displayed as follows[sample]
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" value="All" onclick="Turnthis();"/>All
<input type="radio" value="Top15" onclick="TurnOutthis();"/>Top5
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
</tbody>
</table></div>
Hope this makes sense. For your kind information, i except code only in javascript not in jquery.
The trick is to get the rows you want and put them into an array, then sort the array and put the rows into the table in the right order. The following will sort the rows based on the cell values, so if the first cell value is equal, it uses the second, and so on. The sort may not be stable since it just uses the built–in Array.prototype.sort. If you want to to be stable, that is pretty simple (but generally not required).
Firstly, get the relevant tBody element and rows:
var tBody = document.getElementById('bt_01').tBodies[0];
var rows = tBody.rows;
rows is a live collection so you want to build an array form it (also helps with sorting). The following works fine in modern browsers:
var rowArr = Array.prototype.slice.call(rows);
But will not work in IE 8 and lower, you'll need to use a for loop (just one extra line of code):
var rowArr = [];
for (var i=0, iLen=rows.length; i<iLen; i++) rowArr[i] = rows[i];
To keep the last row as the last, just keep a reference:
var lastRow = rowArr[rowArr.length - 1];
Now sort based on the cell values from the second cell onward:
rowArr.sort(function(a, b) {
var aVal, bVal;
for (var i = 1, iLen = a.cells.length; i<iLen; i++) {
aVal = a.cells[i].textContent || a.cells[i].innerText;
bVal = b.cells[i].textContent || b.cells[i].innerText;
if (aVal != bVal) return aVal - bVal;
}
return 0;
});
Now put the rows into order:
for (var j=0, jLen=rowArr.length; j<jLen; j++) {
tBody.appendChild(rowArr[j]);
}
and finally, put the bottom row back at the bottom:
tBody.appendChild(lastRow);
and you're done. And it's shorter than the offered jQuery alternative (and likely a lot faster). ;-)
It would be best to put footer row in separate tFoot section as you've done with the header.
Edit
If you want to sort based on the sum of the values in each row, the sort part becomes:
rowArr.sort(function(a, b) {
var aSum = 0, bSum = 0;
for (var i = 1, iLen = a.cells.length; i<iLen; i++) {
aSum += parseFloat(a.cells[i].textContent || a.cells[i].innerText);
bSum += parseFloat(b.cells[i].textContent || b.cells[i].innerText);
}
return aSum - bSum;
});
I assume you want the "total" row at the end of the table after sort.Otherwise code can be 10-12 lines shorter.
i come up with this solution.I've commented out every portion for convenience .With a little help form getElementsByTagName,removeChild,createElement,and appendChild methods you can achieve what you are trying to do.It is really simple.I advice you go through it.The main thing is create an array of objects which hold three properties.And the properties are the actual tr element,its sum and the first td element which holds subject1,2,3....and Total string.Then sort them down with Array.prototype.sort() then add them serially to your tbody element
var radio=document.getElementById('radio');
if(radio.checked == true){ //check for radio element is checked or not
radio.checked=false;
}
var table=document.getElementById('bt_01');
var serialTdArr=[]; //array which will hold the array of objects
var storageForTotal='';// store the tr element that has 'Total' as value of its first td element
function Turnthis(e){
var tbody=document.getElementsByTagName('tbody')[0]; //get the current tbody element
var tr=tbody.getElementsByTagName('tr'); //get all tr elements inside tbody
for(i=0;i<tr.length;i++){ // loop over the tr elements
var sum=0;
var td=tr[i].getElementsByTagName('td'); //get all td element inside every tr element
for(j=1;j<td.length;j++){
sum+=parseInt(td[j].innerHTML); // sum them up
}
var firstTd=td[0].innerHTML; //save every subject1,subject2,3,...and Total string to a seperate variable
serialTdArr.push({index:tr[i],sum:sum,pointer:firstTd}); // an object which holds the tr element,its sum and its first td element value is pushed inside serialTdArr
}
var sortedArr=serialTdArr.sort(function(a,b){ // sort them down from higher to lower
if(a.sum < b.sum){
return 1;
}
if(a.sum > b.sum){
return -1;
}
return 0;
});
table.removeChild(tbody); // remove the current tbody
var newTbody=document.createElement('tbody'); // create a new tbody
table.appendChild(newTbody); // append it to table
for(i=0;i<sortedArr.length;i++){
if((sortedArr[i].pointer) != 'Total'){ // if it has no "Total" string then add them to tbody
newTbody.appendChild(sortedArr[i].index); // add to tbody
}else{
storageForTotal=sortedArr[i].index; // 'Total' row will be seperated and stored in a variable to be added later at the end of the table
}
}
newTbody.appendChild(storageForTotal); // add the tr which 'Total' to the last of td element
}
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" id='radio' value="Sort Them All" onchange="Turnthis();"/>Sort Them All
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
This code works and tested on Chrome 30
Non-jQuery version (updated question):
<html>
<body>
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
<tfoot>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tfoot>
</table>
</div>
<input type='button' onclick='sort()' value='sort by sum' />
<script>
function sort() {
var t = document.getElementById('bt_01').children[1]; // tbody
var arr = [];
// find all tr
var trs = t.children;
for(;trs.length;) {
var tr = trs[0];
// find all td and calculate the sum
var sum = 0;
var tds = tr.children;
for(var y in tds) {
var td = tds[y];
var v = +td.textContent;
if (!isNaN(v)) sum += v;
};
// move them to arr
tr = tr.parentNode.removeChild(tr)
arr.push({sum: sum,tr: tr});
};
// sort it
arr.sort(function(a, b) {
if (a.sum < b.sum) return 1;
if (a.sum > b.sum) return -1;
return 0;
});
// attach back the tr in order
for (var z in arr) t.appendChild(arr[z].tr)
}
</script>
</body>
</html>
jQuery version:
<html>
<body>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
<tfoot>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tfoot>
</table>
</div>
<input type='button' onclick='sort()' value='sort by sum' />
<script>
function sort() {
var t = $('#bt_01').find('tbody');
var arr = [];
// find all tr
t.find('tr').each(function(idx, tr) {
tr = $(tr);
// find all td and calculate the sum
var sum = 0;
tr.find('td').each(function(idx, td) {
td = $(td);
var v = +td.text();
if (!isNaN(v)) sum += v;
});
// move them to arr
arr.push({sum: sum,tr: tr.detach()});
});
// sort it
arr.sort(function(a, b) {
if (a.sum < b.sum) return 1;
if (a.sum > b.sum) return -1;
return 0;
});
// attach back the tr in order
for (var z in arr) t.append(arr[z].tr)
}
</script>
</body>
</html>
I have a Table whose <td> values varies depending upon the inputs given in form, I am using Tangle to make a reactive document. Is it posible to detect if the value of <td>changes to any negative number? If so, then it must change its color to red!
Can Javascripting or html tags itself solve this problem?
Please help!
My change will be on profitLossIn1,profitLossIn2,profitLossIn3.
Here is my html:
<table>
<tr>
<th>Name</th>
<th>Cost</th>
<th>Revenue</th>
<th>Result Profit/Loss</th>
</tr>
<tr>
<td><input id='NameInn1' type='text' NAME="NameInn1"></td>
<td><span class="TKNumberField" data-var="CostIn1"></span></td>
<td><b data-var="revenueIn1"> Cost</b></td>
<td><b data-var="profitLossIn1"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn2' type='text' NAME="NameInn2"></td>
<td><span class="TKNumberField" data-var="CostIn2"></span></td>
<td><b data-var="revenueIn2"> Cost</b></td>
<td><b data-var="profitLossIn2"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn3' type='text' NAME="NameInn3"></td>
<td><span class="TKNumberField" data-var="CostIn3"></span></td>
<td><b data-var="revenueIn3"> Cost</b></td>
<td><b data-var="profitLossIn3"> dollars</b></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b data-var="totalRevenueIn"> dollars</b></td>
</tr>
</table>
I am trying this:
var inputs = document.getElementById("profitLossOut1");
console.log(inputs.value);
inputs.onchange = function () {
console.log("Checking IF condition");
if ((parseInt(this.value)).match("-") == true) this.parentNode.style.background = "red";
};
maybe this can be helpful: http://jsfiddle.net/tz7WB/
JQUERY CODE
$(":input").on("change", function () {
if (parseInt($(this).val()) < 0) $(this).closest("td").css("background", "red");
})
try to type any negative number in the inputs
with pure js: http://jsfiddle.net/tz7WB/1/
JS CODE
var inputs = document.getElementsByTagName("input");
for (var x = 0; x < inputs.length; x++) {
inputs[x].onchange = function () {
if (parseInt(this.value) < 0) this.parentNode.style.background = "red";
};
}
Assuming I understand your question correctly, you don't want to check for negative values of the inputs, you want to check for negative values of the tangle-generated text values.
This code should be more of what you're looking for, and it works as long as the text content of your data-var elements starts with the number. If not, the number parsing logic will need to be improved:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(e) {
var $target = $(e.target);
var checkNeg = function(c) {
for(var i=0,$ci; i<c.length; i++) {
$ci = $(c[i]);
if(parseInt($ci.text()) < 0) $ci.css("color", "red");
else $ci.css("color", "black");
}
};
checkNeg($target.parents("table").find("[data-var]"));
});
});
</script>
Consider using knockout.js for your scenario, you can use it to easily format your UI elements according to the underlying data. Take a look at the examples: http://knockoutjs.com/examples/
Add jquery change events for each of input boxes . Below is sample code
$("#NameInn1").change(function(){
var input = $("#NameInn1").val();
if(input<10){
$("#NameInn1").css("background-color","red");
}
});
I have a table within a form that I want to append new rows as the user enters input in the last row of the table.
$('table.form-table').on('input', function() {
var tableID = '#' + $(this).closest('table').attr('id');
if(jQuery(this).closest('tr').is(':last-child')) {
var currTR = $(this).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = jQuery(currTRhtml);
var checkBox = jQuery('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
jQuery(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
And the html code if needed (simplified/trimmed):
<table class="form-table" id="XXX" border="1" cellspacing="0" cellpadding="3">
<thead>
<tr class="main"><th nowrap colspan="3" align="left"
class="border-left border-top border-right">
<h3>XXX</h3></th>
</tr>
<tr>
<th>header</th>
</tr>
</thead>
<tbody>
<tr>
<input type="hidden" name="isnew" value="">
<td >
<input type="text"
name="new_text"
value="">
</td>
</tr>
</tbody>
</table>
The problem is that this works only once and does not continue appending new rows. It's as if the last-child filtering does not get reset...
Any thoughts?
The problem is that you need to use the event's target, rather than "this". Right now "this" refers to the current table, but you need to refer to the current input box and then use closest() to find its parent tr (and :first-child to make sure it's the last one). So your code needs to look more like this:
$('table.form-table').on('input', function(e) {
var tableID = '#' + $(this).closest('table').attr('id');
if ($(e.target).closest('tr').is(':last-child')) {
var currTR = $(e.target).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = $(currTRhtml);
var checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
Notice I'm passing the event as "e" and then referencing the current input box with $(e.target).
Here's a working JS fiddle.
I suspect the problem is that you need to delegate the input event as the appended rows do not exist on $(document).ready(). Try doing something like this to delegate the handler:
$(document).ready(function () {
$('table.form-table tbody').on('input', 'tr', function () {
var self = $(this),
tableID = '#' + self.closest('table').attr('id'),
currTR = self.closest('tr'),
currTRhtml = '<tr>' + currTR.html() + '</tr>',
nextRow = $(currTRhtml),
checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
if (currTR.is(':last-child')) {
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
});
Fiddle: http://jsfiddle.net/KW7ET/