Sum a list of text boxes in jQuery - javascript

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;
}

Related

Storing Key and Value using Javascript in array

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.
I have tried this by creating a method but it is not working perfectly can you please help me..
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
if (chks.length > 0) {
uninvoiced.push(value);
} else {
uninvoiced.pop(key);
}
console.log(uninvoiced);
}
You need to use splice to remove the element from the array
function addCheckboxVAlues(checked){
var split = checked.value.split("|");
var key =split[0];
var value=split[1];
var chks = $("input[name='"+key+"']:checked");
var index = uninvoiced.indexOf(key);
if (chks.length > 0) {
uninvoiced.push(value);
} else if(index > -1){
uninvoiced.splice(index, 1);
}
console.log(uninvoiced);
}
This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this. All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.
That will be hugely more efficient than running a checked selector every time.
The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.
var uninvoiced = [];
function addCheckbox(el) {
var value = el.value.split('|')[1];
if (el.checked) {
uninvoiced.push(value);
} else {
uninvoiced.splice(uninvoiced.indexOf(value), 1);
}
console.log(uninvoiced);
}
foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)">
fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)">
There is a polyfill for indexOf on MDN.

Multiple input and multiple output with onclick eventlistener in javascript

Want to ask :
For example , i have multiple button and when i click on anyone, the value will be shown at the result textbox and the input textbox will back to 0 , need help on check my code :
document.getElementById("plusthevalue").addEventListener('click',function plus()
{
var inputvalue = document.getElementById("Input");
var resultvalue = document.getElementById("Result");
document.write("Result").value = inputvalue + resultvalue;
document.write("Input").value ="0";
});
and, if i want to write a single statement that can include all the button and will display the output depend on the button, how would the code will be?
p/s: i know i can hardwork until i code function for every button but that would be very messy , i want to include all :(
You can assign all your buttons a certain class, then use document.querySelectorAll('.myclass') to grab all of them. Then you can loop through the results to add the event listener to each of them.
Example:
var myButtons = document.querySelectorAll('.myclass');
for (i = 0; i < myButtons.length; ++i) {
myButtons[i].addEventListener('click', function(e) {
// Do stuff
}
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for more info about querySelectorAll.

Javascript (vanilla) - How to specify the type of an element when using querySelectorAll?

How can I specify the type of an element when using querySelecterAll()?
For example, I want to select all the input fields where type=text in a form. Not for styling but for functionality.
This is what I have right now:
var inputGroup = document.getElementById('contactForm');
var inputs = inputGroup.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("blur", checkInput);
}
function checkInput() {
this.value === "" ? this.className = "error" : this.className = "valid";
}
Right now I am also targeting the inputs where the type is set to submit, radio etc. But I just want to target the input elements where the type is set to text.
You can use the attribute selector syntax directly in the call to querySelectorAll:
var inputs = inputGroup.querySelectorAll('input[type="text"]');
This however may miss <input> tags that don't have the type attribute specified at all. You can work around this by also picking up the <input> tags without it in your selector:
var inputs = inputGroup.querySelectorAll('input[type="text"],input:not([type])');

Calculate total of input text fields on a datatable in jsf

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

Javascript - get text between <li> by ID

I'm trying to write some javascript that will grab the inner text of li elements (1-16) and put them into hidden fields.
var myValue9 = document.getElementById("fileName9").value;
oForm.elements["fileName9"].value = myValue9;
<input name="fileName9" type="hidden" id="fileName9" />
<li id="wavName9"> Some Text </li>
How do I return the text in between the <li> and put into the hidden field?
Simple JavaScript:
document.getElementById("fileName9").value = document.getElementById("wavName9").innerText;
You could, in this case, also use innerHTML but that would also give you the HTML the element contains.
LI tags don't have a .value property. Using plain javascript, you could do it this way:
oForm.elements["fileName9"].value = document.getElementById("wavName9").innerHTML;
Or, to do all of them from 1 to 16, you could use this loop:
for (var i = 1; i <= 16; i++) {
oForm.elements["fileName" + i].value = document.getElementById("wavName" + i).innerHTML;
}
Or since you also tagged your post for jQuery, using jQuery you could do it like this:
$("#fileName9").val($("#wavName9").text());
Or, to do all of them from 1 to 16:
for (var i = 1; i <= 16; i++) {
$("#fileName" + i).val($("#wavName" + i).text());
}
Use jQuery to do it.
var myvar = $("#wavName9").html()
I think this will do in for all li's
$("li[id^=wavName]").each(function(){
var $this = $(this);
$this.closest("input[id^=fileName]").val($this.text())
});
Create your li's with id's following such a structure: listitem-n, where n is 1-16 and input fields following the same structure hiddeninputs-n (n = 1-16)
using jfriend00's code, add it in a loop that will traverse 16 times, incrementing a count variable that you will use to transfer the data from list items to hidden inputs
var count = 0;
for( i=0; i < 16; i++){
count ++;
$("form #hiddeninput-"+count).val($("#listitem-"+count).text());
}
Better validate the code, but there's the general idea.
You could also create the hidden fields in javascript from scratch, which would make the code abit more stable IMO as there's less chances of a hidden field missing in the form when the js is executed.
Using jQuery:
$('#fileName9').val($('#wavName9').text());
Note that you can change .text() to .html() to return the HTML structure rather than just the text.
You could automate this for multiple <li>'s like so:
$('li[id^="wavName"]').each(function () {
var number = this.id.replace('waveName', '');
$('#fileName' + number).val($(this).text());
});
This selects all <li>'s who's id starts with "wavName" and stores the text within the <li> tag in the hidden input who's id starts with "fileName" and ends with the same integer as the <li> tag.

Categories

Resources