Calculate total of input text fields on a datatable in jsf - javascript

I have a JSF <h:datatable> with two columns.
column 1 : <h:outputText>, gets populated from bean data.
coulmn 2 : <h:inputText> boxes.
There is a "Total" field outside the table and I want to have it show the total of fields as entered in column2 in realtime. So I did searching around and found out that I need a JavaScript to do this. I am however quite new to JS.
Where I am confused is how to access the value of the input text box. What I have done so far:
function totalFrom() {
var element = document.getElementById('transferFundsForm:fundsFromTable:0:from_transferAmt');
if(element != null){
document.forms['transferFundsForm']['transferFundsForm:totalFrom'].value = document.forms['transferFundsForm']['transferFundsForm:totalFrom'].value+ element;
}
}
As far as I understand, the transferFundsForm:fundsFromTable:0, here 0 represents the first row. How do I refer to the element in column that is being edited?
I have called this function on onblur event of the textBox in column.
Also I read that I can use <f:ajax> for this as well, but I am using JSP instead of Facelets, so I can't use <f:ajax>.

The HTML DOM element representation of <table> element has a rows property which gives you an array of all <tr> elements. The HTML DOM representation of this <tr> element has a cells property which gives you an array of all <td> elements.
So, provided that the 2nd column of the table contains only one <input> element which holds the value you'd like to sum up, and that totalFrom is an <input> element (at least, you're attempting to set the value property and not innerHTML), you could achieve this as follows:
function totalFrom() {
var table = document.getElementById('transferFundsForm:fundsFromTable');
var total = 0;
for (var i = 0; i < table.rows.length; i++) {
var secondColumn = table.rows[i].cells[1];
var input = secondColumn.getElementsByTagName('input')[0];
var value = parseInt(input.value);
if (!isNaN(value)) {
total += value;
}
}
document.getElementById('transferFundsForm:totalFrom').value = total;
}
If the totalFrom is however a <h:outputText id="totalFrom">, then set it as follows instead:
document.getElementById('transferFundsForm:totalFrom').innerHTML = total;

Why don't you use the jsf server side event or user
http://livedemo.exadel.com/richfaces-demo/
it also provide you builtin ajax functionality

Related

Jquery contenteditable for all cells not rows

I create a table by adding rows and columns with JS and Jquery.
This is my code:
function AddColumnToDataTable(){
$('#tableHeader').append("<th> Header </th>").attr("contenteditable", true);
// Add a new ColumnHeader and set the property "editable"
}
function AddRowToDataTable(){
var count = $('#tableHeader').find("th").length;
// Get the count of Columns in the table
var newRow = $('#tableBody').append("<tr></tr>");
// Add a new Row
for(var i = 0; i < count ; i++){
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
// Fill the cells with a default text and set the property "editable"
}
}
So my question is, how can I write the code, that each cell is editable? At the moment, when I click, the whole row goes editable? Each cell should have that property.
I found a code that could help:
//$('table th:nth-child(4)').attr("contenteditable", true)
This makes the 4th header/cell editable, but how can I use it, each new created header/cell is the nth-child?
The jQuery append function doesn't return the new [appended] element, rather it returns the element that was appended to, hence the error in your code. Regardless, it's easier just to set the attribute manually in the append string. So, change this line:
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
To this:
newRow.find('tr').last().append("<td contenteditable="true"> Content </td>")
That should do it
It worked with
$('table td').last().attr("contenteditable", true);

how to get previously selected rows of a bootstrap dataTable while searching

I have used a bootstrap DataTable to show data. At the same time i have a HTML checkbox as a column of that dataTable. I have a submit button to get the selected checkbox's value to do some stuff. I am fetching the following problem while select checkboxes under searching.
When i select all checkboxes and Click Save button I got all the values. It works as my expectation.
But Unexpected occures when i search via built-in search box of bootstrap dataTable.Here is the pictorial view
In this case when i press Save i got just the two value though all other values are still selected. How can i get all the selected values while searching
Here is my jquery code of Save button of getting the checkboxes value
$("#btnSave").click(function () {
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
....
//Other stuff
....
}
Please help me.
When you are doing a search, it is going to check only for the rows, that satisfy the given criteria. So your search logic works like this
if(searchCriteria==true)
{
showValue
}
Even if you had previously selected values it won't be showing all of them, because they don't satisfy the given criteria. Now in this case when you click on Save, it is taking only those rows in the datatable which are checked and satisfy the given criteria, as per your java script.
Now if you still wish, that all selected values should be taken in, there is one way you can try, put the selected values in some kind of List or Set, and place the list object in session. So everytime you click on Save, you can retrieve the List from the session. But I really don't see why you would want to do it, unless you need to retrieve the selected values every time.
I got my job done like this
var table = $('#tblReportList').dataTable();
When i was searching through dataTable, i was getting just the selected values matching the search criteria. But the previously selected values was disappeared. To get the previously selected value i used the following code...
table.$('input[type="checkbox"]').each(function () {
if (!$.contains(document, this)) {
if (this.checked) {
previousVal = previousVal + ',' + this.value;
}
}
});
Now, for getting the selected values of search I used the previous code posted before. And that was
var checkboxes = document.getElementsByName('foo');
var vals = "";
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked) {
vals += "," + checkboxes[i].value;
}
}
So all selected checkbox's values are
var allValues=previousVal+vals;

Get An Element Within a Table Row

Firstly,
If possible, I would like to do this without JQuery, and purely Javascript.
Ok so I have an html table with rows getting added dynamically to it.
In each row is a:
Select Element (id = "ddFields")
Text Input Element (id = "tfValue")
Button Element (no id)
The Button Element removes the row for which it is situated
The Select Element has a default option of "" and then other 'valid' options
The Text Input is added to the row but it is hidden.
All elements are in the same
Basically I would like for the Select Element to show the hidden text input element if the selected index is != 0
so far I have this for my onchange function:
function itemChanged(dropdown) //called from itemChanged(this)
{
var cell = dropdown.parentNode;
var row = cell.parentNode;
var rowIndex = dropdown.parentNode.parentNode.rowIndex;
var index = dropdown.selectedIndex;
var option = dropdown.options[dropdown.selectedIndex].text;
if(index >0)
{
alert(row);
var obj=row.getElementById("tfValue"); //tfValue is the Text Field element
alert(obj);
//row.getElementById("tfValue").hidden = "false"; //doesn't work
//row.getElementById("tfValue").setAttribute("hidden","true"); //doesn't work
}
else
{
alert('none selected');
}
}
Finally figured it out. So here it is:
SCENARIO:
A table that has rows added to it dynamically.
In each row there is a select element and an input text element.
The select element changes text-value of the input text element based on the index of the select element.
in your select element set the onchange function to this:
onchange="selectionChanged(this)"
then create a javascript function shown below:
function selectionChanged(dropdown)
{
//get the currently selected index of the dropdown
var index = dropdown.selectedIndex;
//get the cell in which your dropdown is
var cell = dropdown.parentNode;located
//get the row of that cell
var row = cell.parentNode;
//get the array of all cells in that row
var cells = row.getElementsByTagName("td");
//my text-field is in the second cell
//get the first input element in the second cell
var textfield = cells[1].getElementsByTagName("input")[0];
//i use the first option of the dropdown as a default option with no value
if(index > 0)
{
textfield.value = "anything-you-want";
}
else
{
textfield.value = null;
}
}
Hope this helps whoever. It bugged me for a very long time. Thanks shub for the help! :)
first, I hope you are not repeating your ids. No two items should have the same id.
If you're iterating, create id1, id2, id3.
Also, this is not necessary but I suggest introducing your vars like this:
var a = x,
b = y,
c = z;
If you decide to use jQuery you could just do this:
$('#tableid').on('click','button',function(){
$(this).parent().parent().remove();
});
$('#tableid').on('change', 'select',function(){
if($(this).val()){ $(this).next().show(); }
});
Be sure to change #tableid to match your table's id.
This assumes the text input is the very next element after the select box. If not so, adjust as necessary or ask and I'll edit.

JQuery DataTables How to get selected rows from table when we using paging?

For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}

Sum a list of text boxes in jQuery

I have a form in which there are textbox(s) added dynamically using jquery.
The textbox ids is formed as an array, i.e. Quantity[0], Quantity[1], Quantity[2] ...
I want to add the numbers in these textbox(s) and display the value in another textbox named "total_quantity" preferably when the focus is shifted out of the array textbox.
How can I do it? I dont mind using jQuery or plain javascript, which ever is easier.
I would suggest giving a common class to your quantity fields such that:
<input type="text" class="quantity" onblur="calculateTotal();" />
Then you would be able to define the following function with jQuery:
function calculateTotal() {
var total = 0;
$(".quantity").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
$("#total_quantity").val(total);
}
The onblur event will fire each time the focus is shifted from the quantity fields. In turn, this will call the calculateTotal() function.
If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. This will match all the text boxes that have an id starting with: Quantity[
var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);
Use the following function, if one can't use document.getElementsByName(), as some MVC frameworks such as Struts and Spring MVC use the name attribute of a text to bind the element to a backend object.
function getInputTypesWithId(idValue) {
var inputs = document.getElementsByTagName("input");
var resultArray = new Array();
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute("id") == idValue) {
resultArray.push(inputs[i]);
}
}
return resultArray;
}

Categories

Resources