I have a div structure like below
<div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>
Now how to add all hidden input values in a variable. Thanks
Using Jquery's map function
var myArray = $('#main input').map(function(){
return $(this).val();
}).get();
It will collect all input's values(12 and 12 in this case) to array variable.
See jsfiddle http://jsfiddle.net/GkXUS/1/
If you want to get sum of values you can do the following
var total = 0;
$.each(myArray,function() {
total += parseInt(this,10);
});
var total = 0;
$('#main input[id^="people_"]').each(function(){
total += parseInt(this.value, 10);
});
Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.
total will give you the total of all the input elements value.
I guess you want this:
var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
hidden_value.push( hiddens[ i ].value );
}
You could try something like this:
var peopleData = $("#main input[type=hidden]").serializeArray();
Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation
Using Plain Javascript
var els=document.getElementById('main').childNodes;
var allVal=[];
for(i=0; i<els.length-1; i++)
{
if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value);
}
console.log(allVal); // the array
console.log(allVal[0]); // first value
An example is here.
Related
PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.
So, I have the following jquery code that clones an element when the input value in a certain field increases.
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
}
else $('[id^="novomov"]:last').remove();
});
});
However, it clones a div that contains part of a form with lots of input fields.
<div id="novomov1" class="novomov">
<table id="tab">
<tr name="linear1" id="linear1">
<td>
Cardinalidade:<input type="text" name="card1" id="card1" value=""><br>
Angulo 1:<input type="text" name="param1" id="angulo1" value=""><br>
Angulo 2:<input type="text" name="param2" id="angulo2" value=""><br>
Tamanho:<input type="text" name="param3" id="tamanho1" value=""><br>
Descricao:<input type="text" name="descricao1" id="descricao1" value=""><br>
Tempo:<input type="text" name="tempo1" id="tempo1" value=""><br>
</td></tr></table></div>
I need to change the names of all the cloned div's descendents, in order to pass these paramaters to a data base. I thought of incrementing the names by 1, using the var num in the jquery function. However I'm I little lost.. so, any clues on how to do that? thank you very much!
Code changed to retrieve all the inputs inside the cloned div and change its name/id.
<script>
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
// get all the inputs inside the clone
var inputs = $clone.find('input');
// for each input change its name/id appending the num value
$.each(inputs, function(index, elem){
var jElem = $(elem); // jQuery element
var name = jElem.prop('name');
// remove the number
name = name.replace(/\d+/g, '');
name += num;
jElem.prop('id', name);
jElem.prop('name', name);
});
}
else $('[id^="novomov"]:last').remove();
});
});
</script>
Instead of parsing the id of the element to get the number you should use the data attribute. Also since you are using jQuery you can use .last() to get the last element with that id. Hope this helps.
$('#nmovimentos').on('change', function () {
var direction = this.defaultValue < this.value,
$last = $('#novomov').last(),
$clone,
num;
this.defaultValue = this.value;
if (direction) {
// add id in a data attribute instead of parsing the id
num = parseInt($last.data('id'), 10) + 1;
// set clone id data attribute to have the latest number
$clone = $last.clone().data('id', num);
// add clone after the last div
$last.after($clone);
} else {
$last.remove();
}
});
I have three DIV whose content are integer values and are updated frequently from another source. My main idea here was to take the content of the three divs parse it into float or integer , add them and display the total in another div. I am looking forward to handle the content in div using a onchange() function, because the the content in them will be changing frequently. Below is my code, its currently not working, i will really appreciate it if you give me a hand of help with this.
The content in this divs will be frequently updated using a text input, you can create a text inout that manipulates the first div then displays the whole sum
Thanks in advance.
<script>
function total() {
var value1 = parseFloat($('#div1').innerHTML ()) || 0;
var value2 = parseFloat($('#div2').innerHTML ()) || 0;
var value3 = parseFloat($('#div1').innerHTML ()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body >
<div id="mywraper">
<div id="div1" onchange="total()">
4
</div>
<div id="div2" onchange="total()">
5
</div>
<div id="div2" onchange="total()">
6
</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
</body>
</html>
Use this html()
<script>
function total() {
var value1 = parseFloat($('#div1').html()) || 0;
var value2 = parseFloat($('#div2').html()) || 0;
var value3 = parseFloat($('#div1').html()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
Try this:
function total() {
// fetch text using 'text' method and then convert string into number using '+' operator
var value1 = +$('#div1').text() || 0;
var value2 = +$('#div1').text() || 0;
var value3 = +$('#div1').text() || 0;
var total = value1 + value2 + value3;
$('#total').html(total);
}
http://jsfiddle.net/uxajjk1b/2/
Use text() instead of innerHTML, like so:
<script>
function total() {
var value1 = parseFloat($('#div1').text()) || 0;
var value2 = parseFloat($('#div2').text()) || 0;
var value3 = parseFloat($('#div1').text()) || 0;
var total;
total=value1 + value2 + value3;
$('#total').html(total);
}
</script>
I didn't really want to answer, as this might be difficult to solve due to the fact that we have no idea how the values are updated in the first place. However, I ended up doing relatively extensive example, so here we are.
So as mentioned before, onChange requires user input or action to detect any change. So that means your total() would only trigger once when the page is loaded ( assuming it's placed right before </body> ).
The best method would be to also stick the total() inside the original function that changes the values inside the html elements. This way total() is also triggered each time.
I couldn't resist making the total() more dynamic. This way, if you add or remove those child divs, the javascript won't need to be updated.
Here's a link to the original jsfiddle
var parentContainer = $('#mywraper');
function total() {
var values = {}; // Optional****
var total = 0;
// Loops through parent containers children ( in this case div elements ).
parentContainer.children().text(function( i, val ) {
var value = parseInt( val );
// Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element.
values[ 'child_' + (i+1) ] = value; // Optional****
// Sums up all the values
total += value;
});
// The optional lines enable you independently check each value, for example:
// console.log( values.child_1 )
// Push total into the #total element.
$('#total').html( total );
}
total();
Here's an example where the values are updated with a click event. So what you do is just add the total() inside the click event as well.
function total() {
var parentContainer = $('#mywraper'),
total = 0;
parentContainer.children().text(function( i, val ) {
total += parseInt( val );
});
$('#total').html( total );
}
total();
$('#updateBtn').on("click", function() {
$('#mywraper').children().text(function( i, val ) {
return parseInt( val ) + 1;
});
total();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mywraper">
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
<button id="updateBtn">Update values</button>
I would like to set a value of a <label>, like so:
<label for="idname">Value here...</label>
with Javascript. I have already done this, for the for attribute:
element.setAttribute("for", "idname");
is there something like element.setValue() that I can use to set the value of the label? Thanks!
jsFiddle Demo
Iterate through the label elements looking for the property for="idname" like this:
var labels = document.getElementsByTagName("label");
for( var i = 0; i < labels.length; i++ ){
if( labels[i].outerHTML.indexOf('for="idname"') > -1){
var UseLabelValue = labels[i].innerHTML;
labels[i].innerHTML = "Replace Value";
}
}
<label for="idname">Value here...</label>
<script>
document.getElementsByTagName('label')[0].innerHTML='new value';
</script>
https://developer.mozilla.org/ru/docs/DOM/element.innerHTML
http://javascript.info/tutorial/searching-elements-dom
A label has no value. If you want to set the text, you may use
element.innerHTML = "some text";
I've an html page which has many dynamically created input boxes. The number of text boxes vary each time.
I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.
How can i do it with javascript?
Thanks
In jQuery something like this should work with a few assumptions:
$('.toAdd').live('change', function() {
var total = 0;
$('.toAdd').each(function () {
total += $(this).val();
});
$('#total').val(total);
});
The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.
In pure JS:
var elems = document.getElementsByClassName('toAdd');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += elems[i].value;
}
document.getElementById('total').value = total;
Let me elaborate when I review my notes but here is a high level answer that I believe will work... (My Java Script is very rusty)...
Make the input boxes share an attribute (or use tag) so you can get a collection to walk through no matter the size... Then on the onkeyup event on every input call this function that will sum the totals. Put the result into another entry with the ID you know beforehand...
You will have to validate input because if one of them is not a number then the total will also be "NAN"
Okay here is a complete working example you can build off of that I just threw together: It obviously needs a great deal of polishing on your end...
<html>
<head>
<script language="javascript">
function AddInputs()
{
var total = 0;
var coll = document.getElementsByTagName("input")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
</script>
</head>
<body>
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<span id="Display"></span>
</body>
</html>