i'm making some auto sum input calculator for me, but i have problem, because i don't know how to select multiple inputs which have different names. I know i could just use 'input' instead of exact name, but i need to do calculations just for 5-6inputs not all, so please help me to do it this way..
Code looks now like this:
<script type="text/javascript">
function findTotal(){
var arr = document.getElementsByName('test1');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
So i would like to calculate exactly test1, test2, test3, test4, test5 inputs.
Thanks
You can use multiple attribute selectors with querySelectorAll():
var arr = document.querySelectorAll('[name="test1"], [name="test2"], [name="test3"], [name="test4"], [name="test5"]');
Though, if they share a common class name, you can select them by that:
<input name="test1" class="totaled">
<input name="test2" class="totaled">
<!-- etc. -->
var arr = document.querySelectorAll('.totaled');
Or, if they share a common parent element, you can find them from it:
<div id="the-parent">
<input name="test1">
<input name="test2">
<!-- etc. -->
</div>
var arr = document.querySelectorAll('#the-parent input');
// or
var arr = document.getElementById('the-parent').getElementsByTagName('input');
Related
I'm java script beginner, so do not be angry against me ;)
In order to simplify my code, I would like to generate automatically variables and affect them their current value in order to use them further.
What I have done and works (but I have a lot of changing variable on various documents) :
Html : input a,b,c,... with id a,b,c,...
a = Number($('#a').val());
b = Number($('#a').val());
c = Number($('#c').val());
...
What I'm trying to do :
Html : add a class 'test' to all inputs I want to generate
var elements = document.getElementsByClassName('test');
elementsLength = elements.length;
for (var i = 0 ; i < elementsLength ; i++) {
elements[i].value = Number($("#"+elements[i].id).val());
}
Something must be wrong in the part elements[i].value = Number($("#"+elements[i].id).val());
because when I call the variable a, b or c, it has not been generated.
after the loop,
alert (a);
returns [object HTMLInputElement] instead of the value I would like to get ;(
I'm searching since yesterday, I'm loose.
Thank you for your support guys.
++
Seems you want to persist the value of INPUTS in variable. I would suggest you to create an object i.e. obj and create properties based on input.
var obj = {};
$('button').on('click', function() {
$('.test').each(function() {
obj[$(this).prop('id')] = Number($(this).val());
});
//For debugging
console.clear();
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" class="test">
<input type="text" id="b" class="test">
<input type="text" id="c" class="test">
<button type="button">Click me</button>
I'm writing a JS code that reads the checkboxes in a particular , checks if they're selected, and if yes, appends their value to a string. This is the code that I have:
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str="";
for(var i =0; i< checkboxArr.length;i++){
var cb = checkboxArr[i];
if(cb.checked){
var newVal=cb.value;
str=str.concat(newVal);
str=str.concat(",");
}
}
alert(str);
The string that I get is:
value1
,value2
,value3
How are these newlines coming in the string ?
Also, the occurance of these newlines is random - sometimes they appear, sometimes I get the desired string.
I also tried combining the concat() calls into 1 statement, and I used the += operator as well, but no luck.
Any guidance is earnestly appreciated. Thanks
That's all you need. Use js right :D
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]');
var str = [];
checkboxArr.forEach(function(cb) {
if (cb.checked) str.push(cb.value);
});
alert(str.join(', '));
and if you still have the same result check your html code. It seems like you have line break right after your value in checkbox
check implementation with ES6, not sure why you are getting new line,
var btn = document.getElementById('btn');
btn.onclick = function(){
var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]:checked');
var res = Array.from(checkboxArr).map(cb => cb.value.trim()).join(',')
console.log(res)
}
<div id="div_name">
<input type="checkbox" value="cb_1" />
<input type="checkbox" value="cb_2" />
<input type="checkbox" value="cb_3" />
<input type="checkbox" value="cb_4" />
<input type="checkbox" value="cb_5" />
</div>
<button id="btn">Check</button>
My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})
UPDATED
How would I get all form elements from a form and format them in an object to match the output of the following object(using only javascript)?
var feature = dojo.byId('searchString').value;
var OBJECTID= dojo.byId('OBJECTID').value;
This is the format I need:
var updates = {attributes:{
OBJECTID:OBJECTID,
SubWS:feature
}};
form elements:
<input type="text" id="OBJECTID" value="" />
<input type="text" id="searchString" value="" />
output:
This is my working script, but the output does not match the above "updates". The final version will loop through many more form fields that will sometimes be updated, so i don't want to hardcode the attributes.
var inputs = document.getElementsByTagName("input");
console.log("inputs array", inputs);
var params = {attributes:{}};
for(var i=0; i < inputs.length; i++){
var curr = inputs[i];
if(curr.getAttribute('type')==='text'){
params[curr.getAttribute('name')] = curr.value;
}
}
this is what it looks like on my actual form. As you can see the object is slightly different.
If i've understood you correctly then you need to change the follow line
params.attributes[curr.getAttribute('name')] = curr.value;
By adding .attributes you should match the structure you are after.
I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);