I'm trying to get the number of checkBoxes checked with using the information from an array but I keep getting undefined. I have to use an array, a switch, and must be in JavaScript for this project. I can't use any other programming Language.
How can I get my function to correctly add the checked boxes?
I am also not sure on how I could implement a switch into this function.+
Please help, I've been working on this for about 4 hours, searching everywhere to find a helpful answer.
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project</title>
</head>
<body>
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<th>Directions: Check of the items you think you would enjoy in each section.<br /> Mark as many items that apply.</th>
<tr><td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic1">Repair a car
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic2">Do wood working
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic4">Explore a forest
<br />
</tr></td>
</table><!--End of tblWhichCareer-->
</form><!--End of frmWhichCareer-->
</body>
</html>
My JavaScript
Global Variables
var getCareer = new Array();
getCareer["chkRealistic1"] = 1;
getCareer["chkRealistic2"] = 1;
getCareer["chkRealistic3"] = 1;
getCareer["chkRealistic4"] = 1;
function getRealistic()
{
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
rTotal = getCareer[selectedRealistic.value]
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}//End of function getRealisticCareer()
You missed the fact that this line
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
returns an array of checkboxes with the name chkRealistic (in your example, all four of them).
Instead of assigning the result of the getCareer function to rTotal, you should iterate through the array of HTMLInput in selectedRealistic checking for the .checked property.
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
for (var sel = 0; sel < selectedRealistic.length; sel++)
{
if (selectedRealistic[sel].checked)
rTotal += getCareer[selectedRealistic[sel].value]
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
You can check a running example here: http://codepen.io/pabloapa/pen/jPNPNg
Try using:
document.getElementById("lblRealistic").innerHTML = document.querySelectorAll('input[name="chkRealistic"]:checked').length + "/9 Checked";
Try this:
function getRealistic()
{
var rTotal = 0;
for(i=0; i<document.forms[0].chkRealistic.length; i++){
if(document.forms[0].chkRealistic.item(i).checked){
rTotal++;
}
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}
Here try this also on Plunker: http://plnkr.co/edit/085ZtojBgvumktHwQSGf?p=preview
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<tr>
<th>Directions: Check of the items you think you would enjoy in each section.
<br />Mark as many items that apply.</th>
</tr>
<tr>
<td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic1">Repair a car
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic2">Do wood working
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic4">Explore a forest
<br />
</td>
</tr>
</table>
<!--End of tblWhichCareer-->
</form>
<!--End of frmWhichCareer-->
<script language="JavaScript">
var getCareer = new Array();
getCareer["chkRealistic1"] = 0;
getCareer["chkRealistic2"] = 0;
getCareer["chkRealistic3"] = 0;
getCareer["chkRealistic4"] = 0;
function getRealistic(cbox) {
var rTotal = 0;
var key = cbox.value;
getCareer[key] = cbox.checked ? 1 : 0;
for (var key in getCareer) {
rTotal += getCareer[key];
}
document.getElementById("lblRealistic").innerHTML = rTotal + "/9 Checked"
} //End of function getRealisticCareer()
</script>
Related
I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
I am writing this code, but unable to get anything. Any help is appreciated.
<!DOCTYPE HTML>
<html>
<head>
<script>
function computeMarks() {
var inputElems = document.form1.getElementsByTagName("input");
var count = 0;
for (var i =0; i<=inputElems.length; i++) {
if(inputElems[i].type === "checkbox" && inputElems[i].checked) {
count++;
}
}
alert(count);
}
</script>
</head>
<body>
<form name="form1" id="form1">
<input type="checkbox" name="quiz" value=1 /> Hi
<input type="checkbox" name="quiz" value=1 /> Bye
<input type="checkbox" name="quiz" value=1 /> See ya
<input type="button" onClick="computeMarks()" value="Compute Marks"/>
</form>
</body>
</html>
I have tried to do getElementByName("quiz") but the same thing is happening.
Change i<=inputElems.length to i < inputElems.length. Array indexes run from 0 to length-1. You're getting an error when i is inputElements.length (when your scripts don't work, isn't the Javascript console the first place you look for help?).
DEMOenter link description here
Well what you need to do is just remove = sign from <= in your code.
<!DOCTYPE HTML>
<html>
<head>
<script>
function computeMarks() {
var inputElems = document.form1.getElementsByTagName("input");
var count = 0;
for (var i =0; i<inputElems.length; i++) {
if(inputElems[i].type === "checkbox" && inputElems[i].checked) {
count++;
}
}
alert(count);
}
</script>
</head>
<body>
<form name="form1" id="form1">
<input type="checkbox" name="quiz" value=1 /> Hi
<input type="checkbox" name="quiz" value=1 /> Bye
<input type="checkbox" name="quiz" value=1 /> See ya
<input type="button" onClick="computeMarks()" value="Compute Marks"/>
</form>
</body>
</html>
I recommand the JQuery to do this, it's way easier. Here is an example if you use JQuery in your code instead of plain javascript:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
function computeMarks() {
var counter = 0;
$('input[type="checkbox"]').each(function(){
if($(this).prop('checked'))
{
counter++;
}
});
alert(counter);
}
</script>
</head>
<body>
<form name="form1" id="form1">
<input type="checkbox" name="quiz" value=1 /> Hi
<input type="checkbox" name="quiz" value=1 /> Bye
<input type="checkbox" name="quiz" value=1 /> See ya
<input type="button" onClick="computeMarks()" value="Compute Marks"/>
</form>
</body>
</html>
You can get the reference of the form and loop through it's elements to see if they are checked or not, simply replace your function with this and it should work:
function computeMarks() {
var checked = 0;
var form = document.getElementById("form1");
var index, element;
for (index = 0; index < form.elements.length; ++index) {
element = form.elements[index];
// You may want to check `element.name` here as well
if (element.type.toUpperCase() == "CHECKBOX" && element.checked)
++checked;
}
alert(checked);
}
See the DEMO here
I would recommend you query the elements, and add the event in JavaScript, for example:
var form = document.form1
var button = form.querySelector('[type="button"]')
var checkboxes = form.querySelectorAll('[type="checkbox"]')
var computeMarks = function(els) {
return []
.map.call(els, function(x){return +x.checked})
.reduce(function(x, y){return x + y})
}
button.addEventListener('click', function() {
alert(computeMarks(checkboxes))
})
Demo: http://jsfiddle.net/u59c3d1L/2/
Look at this HTML example:
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
And the resulting output from it:
I hope to send the checked checkbox to the servlet, but i also want to get the order user selected these checkbox.
For example,user A do stuff like : select Cheese,select Butter, select Milk->then Cheese,Butter,Milk will be sent to servlet with this order.
If user B do stuff like : select Cheese,select Butter, deselect Butter, select Milk , select Butter->then Cheese,Milk,Butter will be sent to servlet with this order.
Appreciate.
Check the fiddle for the checkbox order here
I used the following JS Code
checkedOrder = []
inputList = document.getElementsByTagName('input')
for(var i=0;i<inputList.length;i++) {
if(inputList[i].type === 'checkbox') {
inputList[i].onclick = function() {
if (this.checked) {
checkedOrder.push(this.value)
} else {
checkedOrder.splice(checkedOrder.indexOf(this.value),1)
}
console.log(checkedOrder)
}
}
}
Make a global variable to track the order:
var selectOrder = 0;
Bind this function to your onclick event in your inputs:
function onClickHandler() {
var senderId = this.id;
selectOrder = selectOrder + 1;
document.getElementById(senderId).setAttribute('data-order', selectOrder);
}
That will set a data-* (custom) attribute on each one with the order they were checked. So, when you submit your form, you can grab all of the checkboxes and get the order with .getAttribute('data-order'); Don't forget to reset your selectOrder = 0 when you submit so it will reorder them on the next time through.
Try this code.This works better
<html>
<head>
<title>My Page</title>
<script type="text/javascript">
var arr=new Array();
function fnc(myid)
{
if(document.getElementById(myid).checked == true)
{
arr.push(document.getElementById(myid).value);
alert(arr);
}
else
{
var item1=document.getElementById(myid).value;
for(i=0;i<2;i++)
{
if(arr[i]=item1)
{
found=i;
arr.splice(found,1);
}
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.jsp" method="POST">
<div align="center"><br>
<input type="checkbox" name="option1" value="Milk" id="Milk" onchange="fnc(this.id)"> Milk<br>
<input type="checkbox" name="option2" value="Butter" id="Butter" onchange="fnc(this.id)"> Butter<br>
<input type="checkbox" name="option3" value="Cheese" id="Cheese" onchange="fnc(this.id)"> Cheese<br>
<br>
</div>
</form>
</body>
</html>
Here, give this a try.
It maintains an array of all of the options' values, along with the order in which they were clicked. It handles the case where items are already checked when the page loads, by arbitrarily assigning them an increasing index for the order they were clicked in.
It handles items being unselected, it also can provide you with a little more info as a happy side-effect of the way I've done it. You can for instance get back values of 2, 3, 4 for selection order. If I load the page, then select Milk then cheese before unselecting then reselecting Butter, I get back the values 2,3,4 2,4,3 - I can straight away tell that the last selection made was Butter, and that it had previously been the first item selected. Likely useless, but an interesting consequence to me all the same.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv
{
border: 1px solid black;
display: inline-block;
}
</style>
<script>
window.addEventListener('load', mInit, false);
function mInit()
{
var i, inputList = document.getElementsByTagName('input'), n = inputList.length;
var cbCount = 0;
var curOrder = 0;
for (i=0; i<n; i++)
{
if (inputList[i].type == 'checkbox')
{
cbCount++;
var cur = inputList[i];
cur.addEventListener('change', onCbChange, false);
var mObj = {val:cur.value, selOrder:0};
if (cur.checked)
{
mObj.selOrder = ++curOrder;
}
availOptions.push( mObj );
}
}
}
var availOptions = []; // an array to hold objects - { val, selOrder }
function getItem(value)
{
var i, n = availOptions.length;
for (i=0; i<n; i++)
{
if (availOptions[i].val == value)
return availOptions[i];
}
return null;
}
// just clear it's selOrder member
function mUnselect(value)
{
var Item = getItem(value);
Item.selOrder = 0;
}
// iterate through the list, find the highest value of selOrder, increment it and set this item's selOrder to that
function mSelect(value)
{
var i, n = availOptions.length;
var curMax=0;
for (i=0; i<n; i++)
{
if (availOptions[i].selOrder > curMax)
curMax = availOptions[i].selOrder;
}
curMax++;
getItem(value).selOrder = curMax;
}
function onCbChange()
{
if (this.checked)
mSelect(this.value);
else
mUnselect(this.value);
alert(this.value + ': ' + this.checked);
}
function showCurState()
{
var i, n=availOptions.length;
var mStr = '';
for (i=0; i<n; i++)
mStr += availOptions[i].val + ", selOrder: " + availOptions[i].selOrder + "\n"
alert(mStr);
}
</script>
</head>
<body>
<div id='myDiv' align="left">
<br>
<input type="checkbox" name="option1" value="Milk"> Milk<br>
<input type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
<input type='button' onclick='showCurState();' value='Show state'/>
</div>
</body>
</html>
I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});
I am developing this for use in Internet Explorer 8 (because at work we have to use it). I have a page that has a table withing a form. The table has a button to "clone" rows, "AddScheduleRow()". That part works good. Each row has a button to delete that row "DeleteRow(r)". That part works well too. I also have a script to rename/renumber each row, "RenumberRows()". It almost works good. I can rename the text fields (for example what was previously StartDate3 now becomes StartDate2). However, in each row is an input that is type="image" and it is named like you should with any input. The name of it is "StartDateCal". The problem is that during the renaming process, when it hits the image input (TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;), I get a JavaScript error "'TheForm.StartDateCal' is null or not an object". I cannot figure this one out and it's standing in the way of moving on.
What can I do to try to rename an < input type = image /> ?
Below is the necessary code:
HTML
<html>
<head>
</head>
<body>
<form name="UpdateSchedule" method="post" action="DoSchedule.asp">
<input type="hidden" name="NumRows" value="0">
<input type="hidden" name="RowsAdded" value="0">
<table id="ClassScheduleTable">
<tr id="ScheduleRow" style="display:none;">
<td>
<input type="text" name="RowNum" value="0" size="1" onclick="alert(this.name)">
</td>
<td>
<b>Start Date</b> <input type="text" name="StartDate" value="" onclick="alert(this.name);" size="8">
<input type="image" name="StartDateCal" src="http://www.CumminsNorthwest.com/ATT/Img/Calendar3.png" style="border-style:none;" onClick="alert('name = ' + this.name);return false;">
</td>
<td>
<input type="button" value="Del." name="DelRow" class="subbuttonb" onclick="DeleteRow(this);">
</td>
</tr>
<tr>
<td colspan="3" style="text-align:right">
<input type="button" value="Add Class Date" class="SubButton" onclick="AddScheduleRow();">
</td>
</tr>
</table>
</form>
</body>
<script language="JavaScript">
JS
var TheForm = document.forms.UpdateSchedule;
var NumRows =0;
var RowsAdded =0;
function AddScheduleRow(){
NumRows++;
TheForm.NumRows.value = NumRows;
RowsAdded++;
TheForm.RowsAdded.value = RowsAdded;
var TableRowId = "ScheduleRow";
var RowToClone = document.getElementById(TableRowId);
var NewTableRow = RowToClone.cloneNode(true);
NewTableRow.id = TableRowId + NumRows ;
NewTableRow.style.display = "table-row";
var NewField = NewTableRow.children;
for (var i=0;i<NewField.length;i++){
var TheInputFields = NewField[i].children;
for (var x=0;x<TheInputFields.length;x++){
var InputName = TheInputFields[x].name;
if (InputName){
TheInputFields[x].name = InputName + NumRows;
//alert(TheInputFields[x].name);
}
var InputId = TheInputFields[x].id;
if (InputId){
TheInputFields[x].id = InputId + NumRows;
//alert(TheInputFields[x].id);
}
}
}
var insertHere = document.getElementById(TableRowId);
insertHere.parentNode.insertBefore(NewTableRow,insertHere);
RenumberRows();
}
AddScheduleRow();
function DeleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("ClassScheduleTable").deleteRow(i);
NumRows--;
TheForm.NumRows.value = NumRows;
RenumberRows();
}
function RenumberRows(){
var TempCounter = 0;
for (var i=0;i<=RowsAdded;i++){
if (TheForm.RowNum[i]){
TempCounter++;
TheForm.RowNum[i].name = "RowNum" + TempCounter;
TheForm.RowNum[i].value = TempCounter;
TheForm.StartDate[i].name = "StartDate" + TempCounter;
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
}
}
}
</script>
</html>
might be to do with your DTD,
try HTML4 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
You can use
document.getElementsByName('StartDateCal')[i].name = "StartDateCal" + TempCounter;
instead of
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;