how to access checkboxes and their values with getElementsByName - javascript

Suppose I have the following section of a form:
<td>
<p>
<input type="checkbox" name="faddon" onchange="iaddon()" value="89.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="29.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="49.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="39.00" />
</p>
</td>
<td>
<p>
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" />
</p>
</td>
Every time the user selects or deselects a checkbox, I need the script to recalculate the variable addon to the total of all values of the boxes which are checked. This is the code I came up with first, but it does not appear to work for me:
function iaddon() {
addon=0;
av=document.getElementsByName("faddon");
for (e=0;e<av.length;e++) {
if (av[e].checked==true) {
addon+=av[e];
}
}
}
The script keeps returning NaN as the value of addon. At first, I wondered if javascript was reading the values as strings and not integers, but adding a (x)*1 around av[e] did not fix this. Then, I read a little more into getElementsByName and read about it possibly not being a typical array, but instead a nodeList.
I'm new to Javascript and can't figure out after hours of googling how to manipulate this nodeList. Any help is appreciated. I'd like to keep the 8 checkboxes in seperate table cells, so using something like childNodes wouldn't exactly work here, as far as I can tell. I also would like to steer clear of any jQuery at this point...I'm still learning and I want to make sure I understand how to do it in plain old javascript first. Thanks!

You need to use the value property and also parse it to a number.
e.g:
function iaddon()
{
addon = 0;
for (e = 0; e < av.length; e++)
{
if (av[e].checked == true)
{
addon += parseInt(av[e].value, 10);
}
}
}

av[e] will return the element not the value of the element there for addon is not a number.
I believe you want to use av[e].value
also note that since you set addon=0 at the start of the function the value of addon will always only be the value of av[e].value during the function call.
function iaddon() {
addon=0;
av=document.getElementsByName("faddon");
for (e=0;e<av.length;e++) {
if (av[e].checked==true) {
addon+=av[e].value;
}
}
}

btw, obtrusive js
<input type="checkbox" name="faddon" onchange="iaddon()" value="89.00"/>
is very depressive to maintain your code, for both js and html code are written together.
Try to write unobtrusive js code like:
In html:
<input id="index1" type="checkbox" name="faddon" value="89.00"/>
In js:
$('index1').click(function() {
// Edit your function
});

Related

jQuery looping checkboxes

I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.
When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.
The HTML looks like this:
<input type="checkbox" id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
There are about 40 of these checkboxes. What I'm looking for is a string like:
"pdfam_711131, pdfam_711341"
I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.
$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););
A simple way is to use .map() to make an array of the IDs, then use .toArray().join(", ") to get your string.
var s = $('input:checkbox[id^="pdfam_"]:checked')
.map(function(i, el) { return el.id })
.toArray()
.join(", ");
console.log(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
You can get all those are selected followed by Join.The get() method returns a specified element from a Map object.
console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
return this.id || null;
}).get().join(','))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />

Copy multiple input fields to other matching input fields with jQuery/Javascript

I have a dummy form and the actual form in which at some point I want to copy all the input values from the dummy form across to the real form.
The dummy fields will have the same names as the real form (so I can match them up).
So in dummy form:
<input name="item1" value="field1" />
<input name="item2" value="field1" />
<input name="item3" value="field1" />
and in real form:
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
I assume I'll need to iterate over each input in dummy form (using jQuery .each() ?) while collecting the name and value in an JS object.
Then iterate over each input in the real form, matching the name as the selector and setting the value (perhaps this can be done in the one .each() function ???)
I've started with the following code which only grabs the values (and index) into an array, but because I need two values (name and value, and index is irrelevant) I assume I'll need an object not an array, but really not sure where to begin with that.
var inputValues = [];
$("#dummyForm input").each(function() {
inputValues.push($(this).val());
});
Any help or advice much appreciated.
Map them like
$('#DummyForm [name]').each(function() {
var name = $(this).attr('name');
$('#RealForm [name="' + name + '"]').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form id="DummyForm">
<input name="item1" value="field1" />
<input name="item2" value="field2" />
<input name="item3" value="field3" />
</form>
<form id="RealForm">
<input name="item1" value="" />
<input name="item2" value="" />
<input name="item3" value="" />
</form>
You could do something like below:
$('#dummy input').each(function(){
if($('#real input[name='+$(this).prop('name')+']').length == 1)
$('#real input[name='+$(this).prop('name')+']').val($('#dummy input[name='+$(this).prop('name')+']').val())
});
Here is my Fiddle...

Javascript Checkbox Validation not Checking if Ticked

I've looked through a lot of the questions that people have already asked on this, but I cannot find a solution that has helped me.
I'm a beginner to programming so know little about what to do, I have four check boxes and to submit the form, you have to select at least one of them, but no message comes up and the form is able to be submitted without one of the boxes being ticked.
This is my code below:
<tr>
<td align="right">
<label for="erdbeersocken"><p>Erdbeersocken<sup>*</sup>:</label>
<br>
<label for="armstulpen">Armstulpen<sup>*</sup>:</label>
<br>
<label for="cupcakes">Cupcakes<sup>*</sup>:</label>
<br>
<label for="babykleidung">Babykleidung<sup>*</sup>:</label>
<br>
</td>
<td align="left">
<form action="../" onsubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX_2" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX_3" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX_4" value="Babykleidung">
<br>
<input type="SUBMIT" value="Submit!">
</td>
</tr>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.CHECKBOX_1.checked == false or
theForm.CHECKBOX_2.checked == false or
theForm.CHECKBOX_3.checked == false or
theForm.CHECKBOX_4.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
Which looks like: Text here (Checkbox here)
I'm using Notepadd++ more advanced code does not seem to work, so if anyone could help me with simplified JavaScript, I would really appreciate it. :)
function checkCheckBoxes(theForm) {
if ($("input[type='checkbox']:checked").length){
return true;
}else{
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
}
For your form, you should give all the checkboxes the same name but give each checkbox a different value -- this will create an array for your checkboxes (see note at bottom of response if you don't yet know what an array is):
<input type="CHECKBOX" name="CHECKBOX" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Babykleidung">
then in your confirm submit function you want to use a for loop with two nested if statements to check if a checkbox has been checked. I'll give you an example of some code I recently did:
var interestsSelected = false;
for (var i = 0; i < document.forms[0].interests.length; ++i ) {
if (document.forms[0].interests[i].checked == true) {
interestsSelected = true;
break;
//code gives go ahead for submission because at least one checkbox has been checked
}
}
if (interestsSelected !=true) {
window.alert("You must select at least one hobby or interest");
return false;
//code Woot woot woot! It all works!
}
This was my form section for the checkboxes:
<input type="checkbox" name="interests" value="technology" />Technology <br />
<input type="checkbox" name="interests" value="arts" />The Arts <br />
<input type="checkbox" name="interests" value="music" />Music <br />
<input type="checkbox" name="interests" value="film" />Movies <br/>
<input type="checkbox" name="interests" value="shopping" />Shopping <br />
<input type="checkbox" name="interests" value="outdoor" />Camping <br />
<input type="checkbox" name="interests" value="garden" />Gardening <br />
As a fellow beginner :) I often find it useful if everything is spelled out in as simple a language as possible so I'm going to provide some details here that you might or might not already know.
Anytime you create a form, an array for the form is automatically created (you won't see it listed anywhere, the browser will automatically create one when it accesses the form data BUT you can (should) refer to it in your coding). So if you have one form on your page you will have an array forms[0], if you have two different forms on your page then the first form will have an array forms[0] and the second form will have an array forms[1], each containing all of the elements in the respective forms.
If you name all your checkboxes the same name, you are essentially creating an array within an array -- the big Mama Bear array is forms[0] and nestled inside her is the Baby Bear array (your checkbox name[]).
In order to reference the Baby Bear array, you have to acknowledge the Mama Bear array first: that is why in the code example I gave above, you see "document.forms[0]" (the Mama Bear array) followed by ".interests[i]" (the Baby Bear array).
Hope this helps :)
HTML for my example
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>Select a box</p>
<form id="aform">
<input type="checkbox">
<input type="checkbox">
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="test.js"></script>
</body>
</html>
And the javascript in its own file (always seperate code from css and from html)
window.onload=function() {
$("#aform").change(function () {
alert('a box is checked');
})
};

Get particular value for each <input>

So this is the case.
I have 2 <input> inside <td> which has unlimited number. For example :
<td>
<input type="text" name="cust_name" onchange="check(this)" />
<input type="hidden" name="cust_id" value="10" />
</td>
<td>
<input type="text" name="cust_name" onchange="check(this)" />
<input type="hidden" name="cust_id" value="12" />
</td>
......
this in check(this) containing cust_name value. But how can I get particular cust_id value with same function? (check())
Delineation :
function check(part_element){
console.log($(part_element).val());
console.log(getting particular cust_id value); //here is the part
}
You can use next
function check(part_element){
console.log($(part_element).val());
console.log($(part_element).next().val());
}
you can use .next() to find the next sibling, in this case it is the cust_id element
function check(part_element){
console.log($(part_element).val());
console.log($(part_element).next().val()); //here is the part
}
This already has an accepted answer, but in this case I'd argue that using jQuery doesn't make this any easier, possibly even more complicated:
function check(el) {
console.log(el.value);
console.log(el.nextSibling.value);
}

How to set up groups of checkboxes which affect each other

Sorry for the ambiguous title, but it's quite hard to condense what I'm trying to do into a few words. Here's exactly what I'm trying to do:
I want to have a series of groups of checkboxes. One would be gender, with checkboxes for Male and Female, one would be Region, with checkboxes for North, East, South and West and so on.
The aim is to allow the user to select say, Male or Female, but as soon as they put a check in a checkbox of another group e.g. any of the Region checkboxes, all of their previous 'checks' from all other groups are removed.
The point is to only allow the user to select from one group of checkboxes at a time.
I can only think of checking which checkboxes have been marked on click using javascript, but was wondering if there was a simpler way which I may be missing.
I've also thought that maybe a hidden radio button for each group could work.
If anyone has a more elegant solution I'm eager to hear it.
Its been a long time since I've done any pure Javascript, libraries like jQuery make this kind of thing so easy. Anyway, something a bit like the following might work, you'd need to test it in a few browsers and tweak to what you need.
<form name="theForm">
<input type="checkbox" id="male" name="theGroup" onClick="clearGroup(this);">male
<input type="checkbox" id="female" name="theGroup" onClick="clearGroup(this);">female
<br />
<input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
<input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
<input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
<input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>
<script>
function clearGroup(elem) {
var group = document.theForm.theGroup;
for (var i=0; i<group.length; i++) {
if (group[i] != elem) {
group[i].checked = false;
}
}
}
</script>
Here is a working example to play around with.
You could do the equivalent thing in jQuery as simply as
$('input:checkbox').click(function() {
$(this).siblings(':checked').attr('checked', false);
});
and you have no browser compatibility issues to worry about.
Managed to figure it out with a little help from fearofawhack planet. Seems really simple now.
Heres a link to the JSFiddle http://jsfiddle.net/aeeN4/
if you have different groups you can use this code below.
<script>
function clearGroup(elem) {
//alert(elem.name);
var group = document.getElementsByName(elem.name);
for (var i=0; i<group.length; i++) {
if (group[i] != elem) {
group[i].checked = false;
}
}
}
</script>
<form name="theForm">
<input type="checkbox" id="male" name="theGroup2" onClick="clearGroup(this);">male
<input type="checkbox" id="female" name="theGroup2" onClick="clearGroup(this);">female
<br />
<input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
<input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
<input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
<input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>

Categories

Resources