I have a form with radio buttons that I'm using javascript to loop through and return the sum of all the radio buttons to an input element at the bottom of the page. The script I'm using is this and it works fine.
<script type="text/javascript">
function checkTotal() {
var radios = document.querySelectorAll('input[type=radio]'),
sumField = document.querySelector('input[type=text]');
var sum = 0;
for (var i = 0, len = radios.length - 1; i <= len; i++) {
if (radios[i].checked) {
sum += parseInt(radios[i].value);
}
}
sumField.value = sum;
}
</script>
Here's my form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire.htm
However I need to build another form where there are several questions in different groups and I need to sum the totals for each group separately and post them to their corresponding input elements on the page accordingly. Here's my new form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire100913.htm
I'm not an advanced javascript user but do have a pretty good understanding of programming itself (I think, lol) My head tells me that I should be able to simply declare a unique var for each different group and a unique element to post it's results to and use the same loop (with correct vars for each group) for each group. But when I add [name="elements name"] as the identifier for the document.querySelectAll it grabs the elements with that name only and if I name the elements themselves the same name the radio buttons loose their inherent property of only letting one radio button per question be selected at a time? I've also tried creating a class id for each group and tried to use it as the identifier in the document.querySelectAll and it doesn't seem to work at all then. Any help is greatly appreciated..
As per my understanding of question, below is my answer. And here is the fiddle http://jsfiddle.net/8sbpX/10/.
function enableQ(cls) {
var ele = document.querySelectorAll('.' + cls)[0],
ev = (document.addEventListener ? "#addEventListener" : "on#attachEvent").split('#');
ele[ev[1]](ev[0] + "change", function () {
var radios = ele.querySelectorAll('[type="radio"][value="1"]:checked').length;
ele.querySelector('[type="text"]').value = radios;
});
}
enableQ("rad-grp");
Related
On my page with payment I need two inputs with total payment value:
- one that the client can see
- another one which is hidden.
I wrote a code which pass price of every element to the input when a client check a box with a product they want to pay for, but it works only with the one input.
I was trying to use different options (like getElementsByName and getElementsByClassName) but I am learning JS now and I have no idea how to solve this problem. :(
function select(selector, parent){
return Array.from((parent||document).querySelectorAll(selector));
}
var inputs = select('.sum'),
**totalElement = document.getElementById('payment-total');**
function sumUpdate(){
totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
WHAT I TRIED:
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total, payment-total2')[0][1];**
var inputs = select('.sum'),
**totalElement = document.getElementsByName('payment-total).getElementsByName('payment-totalTwo);**
If I'm understanding you right, you want to put the computed value in both the id="payment-total" element and the id="payment-total2" element.
If so, just do what you've already done for payment-total, but for payment-total2 as well, see *** comments:
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total'),
totalElement2 = document.getElementById('payment-total2'); // ***
function sumUpdate(){
//vvvvvvvvvvvvvvvvvvvvvv---- ***
totalElement2.value = totalElement.value = inputs.reduce(function(result, input){
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(0);
}
I don't immediately see the reason for having both a visible and a hidden input, but if you need that for some reason, that's how you'd do it.
If it got to the point there were three or more elements you wanted to update, I'd probably give them all a class and select them the way you've selected your .sum elements, then compute the total once and assign it to all of them in a loop. But for just two, repeating the lookup and assignment seems fine.
Hello I am having a small problem, I have about 4 select boxes each with different values in them for the user to choose from these are created dynamically in a loop within java script so they all share the same id.
I want to print each value selected dynamically so when you select from select box 1 print its value then when selecting box 2's option the first value is overridden.
The code I have now only works for the first select box, can anyone help me get it working for them all?
for(var i=0; i<5; i++){
var a=document.createElement("select");
aa.setAttribute('id', 'boxes');
//..addoptions in another loop then in the same loop I have
aa.onchange = function(){ tester();};
}
function tester(){
var i = document.getElementById("boxes");
var ii = i.selectedIndex;
document.getElementsById("pTag").innerHTML=i.options[ii].value
}
Javascript only please
Modify your code as follows it should fix your problem. Notice that aa.onchage = tester and not aa.onchange = tester() the reason is because you are assigning aa.onchange to the function tester and not its return value.
for(var i=0; i<5; i++){
var a=document.createElement("select");
aa.setAttribute('id', 'boxes'+i);
//..addoptions in another loop then in the same loop I have
aa.onchange = tester;
}
function tester(event){
document.getElementsById("pTag").innerHTML = event.target.value;
}
I was wanting to count the occurrences of input fields that has a class name of text where that text input contains a specific value.
document.getElementById('c_files').getElementsByClassName('text').length;
So far this counts all textboxes with the class name of text but how can i make it value specific, say if i have 50 textboxes but i only want to count the ones where the value of that textbox contains abc somewhere within the string.
Thanks.
Edit: Thank you everyone for your time and answers, i have voted you all up, but i prefer John Bupit's solution out of them all so thats the one i will accept. Thanks again.
You can iterate over the elements and see which ones have the desired value:
var elems = document.getElementById('c_files').getElementsByClassName('text');
var count = 0;
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.match(/abc/)) count++;
}
You can select all textboxes first and after that filter those matching your criteria. For example, by using Array.prototype.filter method:
var allText = document.getElementById('c_files').getElementsByClassName('text'),
filtered = [].filter.call(allText, function(textbox) {
return textbox.value.indexOf('abc') > -1;
});
Above code will produce and array of text elements where value contains substring "abc".
Hi I think you need to review this SO post-
https://stackoverflow.com/a/9558906/3748701
https://stackoverflow.com/a/10095064/3748701
This is something which would help in getting your solution.
You'll need to loop over all of the text boxes with the specified class and calculate it from there.
Something like the following logic should work:
var counter = 0;
var inputElements = document.getElementById('c_files').getElementsByClassName('text').length;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements.value == "someText") {
counter++;
}
}
I am trying to do the folowing with Asp.net 3.5/IIS
A web form with a top level repeatable form. So basically a Order->Products->ProductsParts kinda of scenerio. Order is only one. Product is repeatable. Each product has repeatable products parts. The product and product part have a whole bunch of fields so I cannot use a grid.
So, I have add/remove buttons for Product and within each product add/remove buttons for each product part.
That is my requirement. I have been able to achieve add/remove after some research using jquery/js. How, do i capture this data on the server? Since javascript is adding and removing these controls they are not server side and I don't know how to assign name attributes correctly. I am trying following javascript but it ain't working:
function onAddProperty(btnObject){
var previous = btnObject.prev('div');
var propertyCount = jquery.data(document.body, 'propertyCount');
var newDiv = previous.clone(true).find("*[name]").andSelf().each(function () { $(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr)); }); ;
propertyCount++;
jquery.data(document.body, 'propertyCount', propertyCount);
//keep only one unit and remove rest
var children = newDiv.find('#pnlUnits > #pnlUnitRepeater');
var unitCount = children.length;
var first = children.first();
for (i = 1; i < unitCount; i++) {
children[i].remove();
}
newDiv.id = "pnlPropertySlider_" + propertyCount;
newDiv.insertBefore(btnObject);
}
I need to assign name property as array so that I can read it in Request.Form
Fix for not updating ids not working:
var newDiv = previous.clone(true).find("input,select").each(function () {
$(this).attr({
'name': function () {
var name = $(this).attr('name');
if (!name) return '';
return name.replace(/property\[[0-9]+\]/, 'property' + propertyCount);
}
});
}).end().insertBefore(btnObject);
The issue looks like the following line:
$(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr));
This statement doesn't do anything. Strings in JavaScript an immutable, and .replace only returns the string with something replaced.
You would then have to actually set the attr("name") to the new string that has the replaced value:
http://api.jquery.com/attr/
I can't help much more without seeing your HTML.
I am trying to loop through Radio groups and validate that the user has made a selection using Javascript. The radio groups are dynamic so the field names are unknown at runtime, and the number of radio groups will also be unknown. After the user has made a selection for each radio group, then process the form.
You can have a map to find the field names that are not checked.
function add() {
remaining[this.name] = true;
}
function remove() {
delete remaining[this.name];
}
var form = $(this), remaining = {};
form.find(':radio').each(add).filter(':checked').each(remove);
Then the remaining variable will be an object that holds the names of the radio group that the user hasn't checked.
If it is an empty object, then the user has selected all groups.
For a working example, look here: http://jsfiddle.net/thai/qtJsJ/1/
You could select all radio buttons using the 'input:radio' selector and then make sure that for each distinct name a value is set.
$(document).ready(function() {
$(this).find("input:radio").each(...)
}
with pure javascript you could try something like
var elements = document.getElementsByTagName("input");
for(var i = 0; i<elements.length; i++)
{
if(elements[i].type === "radio")
{
//dostuff
}
}