How to remove static array after uncheck checkbox in jquery - javascript

I have two checkboxes, and I want whenever I click on any checkbox then their values (static array) should be inserted into "final" array (empty array). If I uncheck that checkbox then its value (static array) should be remove from "final array".
Right now I am inserting/pushing "static" array into blank array (final array), but I want to know that how can I remove this "static" array after uncheck checkbox ?
var myarray = [];
var model = ["Height", "size", "bust"];
var Hostess = ["Height", "bust"];
$("input:checkbox.country").click(function() {
var value = $(this).val();
if (!$(this).is(":checked"))
alert('you are unchecked ' + $(this).val());
else
myarray.push(model);
});
console.log('Final array is ', myarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="country" name="interest" value="Hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>

As noted in the comments, you can rebuild the array each time.
Assuming you want a 1-dimensional array rather than an array of arrays, you can use
myarray.push(...modelarray);
to add the array items.
I've used a switch here to match the checkbox value with the array variable, but a better solution for this part (already provided in another answer) is to use an object and get the array by key. I've kept this with the switch to show the difference and use of .push(...array)
var myarray = [];
var modelarray = ["A", "B", "C"];
var hostessarray = ["X", "Y"];
$("input:checkbox.country").click(function() {
// rebuild myarray
myarray = [];
$("input:checkbox.country:checked").each(function() {
switch ($(this).val())
{
case "model":
myarray.push(...modelarray);
break;
case "hostess":
myarray.push(...hostessarray);
break;
}
});
console.log('Updated array is ', myarray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="hostess" class="country" name="interest" value="hostess">
<label for="hostess">hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>
Also in fiddle: https://jsfiddle.net/cwbvqmp4/

You need to generate the array from the checked boxes each time
I suggest an object, where you can get the values based on key
I renamed the class (country) - it does not match the actual values (attributes based on interest)
let myArray;
let interests = {
"model": ["Height", "size", "bust"],
"hostess": ["Height", "bust"]
}
$("input:checkbox.interest").on("click", function() {
myArray = $("input:checkbox.interest:checked")
.map(function() { console.log(this.value,interests[this.value])
return interests[this.value]
}) // get checked boxes and their interests
.get() // return an array
.filter(val => val); // remove empty slots
console.log('Final array is ', myArray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="interest" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="interest" name="interest" value="hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>

Use conditions like below while you have static array for both checkboxes.
var myarray = [];
var model = ["Height", "size", "bust"];
var Hostess = ["Height", "bust"];
$("input:checkbox.country").click(function() {
var value = $(this).val();
if(value === "model"){
if (!$(this).is(":checked")){
myarray.splice(myarray.indexOf(model), 1);
}
else{
myarray.push(model);
}
}
else if(value === "Hostess"){
if (!$(this).is(":checked")){
myarray.splice(myarray.indexOf(Hostess), 1);
}
else{
myarray.push(Hostess);
}
}
console.log('Final array is ', myarray);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<fieldset>
<legend>Choose your interests</legend>
<div>
<input type="checkbox" id="model" class="country" name="interest" value="model">
<label for="model">model</label>
</div>
<div>
<input type="checkbox" id="Hostess" class="country" name="interest" value="Hostess">
<label for="hostess">Hostess</label>
</div>
<div>
<button type="submit">Submit form</button>
</div>
</fieldset>
</form>

Related

How can I delete an element in an object?

I have a checkbox which add an id of his value in array when checked and I want to delete this value when I uncheck it
I tried to remove my id with and indexOf() + splice() but I can't use indexOf() because I'm using an object
Some one have an idea to how can I delete my id when I uncheck my checkbox,
or if there is a trick to use indexOf with an object?
there is my script :
$(document).ready(function() {
const formInputIds = $('form#export input[name="ids"]');
$('.exportCheckbox:checkbox').on('change', function() {
const announceId = $(this).data('id');
if (this.checked) {
formInputIds.push(announceId);
console.log(formInputIds);
} else {
const index = formInputIds.val().indexOf(announceId);
if (index > -1) {
formInputIds.val().splice(index, 1);
}
console.log(formInputIds);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<some data of product displayed>
<input type="checkbox" data-id="{{annonce._id}}" class="exportCheckbox"/>
there is the console.log of formInputIds with 3 ids :
Consider the following.
$(function() {
var formInputIds;
function getChecked(target) {
var results = [];
$("input[type='checkbox']", target).each(function(i, elem) {
if ($(elem).is(":checked")) {
results.push($(elem).data("id"));
}
});
return results;
}
$('.exportCheckbox').on('change', function(event) {
formInputIds = getChecked($(this).parent());
console.log(formInputIds);
});
$("#export").submit(function(event) {
event.preventDefault();
console.log(formInputIds);
$("[name='ids']", this).val("[" + formInputIds.toString() + "]");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<div class="some content">
<input type="checkbox" data-id="1001" class="exportCheckbox" />
<input type="checkbox" data-id="1002" class="exportCheckbox" />
<input type="checkbox" data-id="1003" class="exportCheckbox" />
<input type="checkbox" data-id="1004" class="exportCheckbox" />
<input type="checkbox" data-id="1005" class="exportCheckbox" />
<input type="checkbox" data-id="1006" class="exportCheckbox" />
</div>
This way, you build the Array based on just the checked items. No need to find and slice the exact item.

Remove undefined value out of an array

When you check an item, it stores the value into an array. When you uncheck the item, it creates an undefined value within the array.
This is not too much of an issue, but having the empty value inside the array counts as a length value which I'm trying to remove. I'm wondering how to remove unchecked array items without storing them as undefined inside the array.
const list = Array.from(document.querySelectorAll("input[type='checkbox']"));
const specArr = []
function check(e) {
// a) If checked than add value into array
if (e.target.checked == true) {
specArr.push(`${e.target.value}`);
console.log(specArr);
// b) If unchecked than remove index from array
} else if (e.target.checked === false) {
let index = specArr.indexOf(e.target.value);
if (index != -1) {
delete specArr[index]
console.log(specArr);
}
}
}
list.forEach(function (listItems) {
listItems.addEventListener('change', check)
})
<form class="form specialization">
<p> <u> Select Item </u> </p>
<br>
<div class="list">
<div class="list-items">
<input type="checkbox" name="specialization" value = "Item-1">Item-1
<br>
<input type="checkbox" name="specialization" value="Item-2">Item-2
<br>
<input type="checkbox" name="specialization" value="Item-3" >Item-3
<br>
<input type="checkbox" name="specialization" value="Item-4" >Item-4
</div>
</form>
You are using delete. As per the delete docs:
Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().
delete deletes the object property, but does not reindex the array or update its length.
Use Array.prototype.splice() instead.
const list = Array.from(document.querySelectorAll("input[type='checkbox']"));
const specArr = []
function check(e) {
// a) If checked than add value into array
if (e.target.checked == true) {
specArr.push(`${e.target.value}`);
console.log(specArr);
// b) If unchecked than remove index from array
} else if (e.target.checked === false) {
let index = specArr.indexOf(e.target.value);
if (index != -1) {
specArr.splice(index, 1);
console.log(specArr);
}
}
}
list.forEach(function(listItems) {
listItems.addEventListener('change', check)
})
<form class="form specialization">
<p> <u> Select Item </u> </p>
<br>
<div class="list">
<div class="list-items">
<input type="checkbox" name="specialization" value="Item-1">Item-1
<br>
<input type="checkbox" name="specialization" value="Item-2">Item-2
<br>
<input type="checkbox" name="specialization" value="Item-3">Item-3
<br>
<input type="checkbox" name="specialization" value="Item-4">Item-4
</div>
</form>

JQuery/JS Input Iteration

I am getting incorrect results from my logic and I'm not sure why. Any recommendations would be highly appreciated.
I have dynamically created cards with 1-3 inputs per card. I am trying to iterate through the cards and collect the input values for each individual card but instead I keep getting the input values for all the cards for each iteration
html
<div class="card">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card">
<input type="hidden" class="sample" value="A">
</div>
js
arr = []
$('.card').each(function (i, obj) {
$('.sample').each (function (i, obj) {
val = $(this).val()
arr.push(val)
})
})
I was expecting arr[A, B] and arr[A]
but i get arr[A, B, A] and arr[A, B, A]
You are getting this result due to inner loop is executing for all samples div present into HTML.
Use $(obj).find('.sample') instead of $('.sample'). It will execute for sample div within card div.
var arr = []
$('.card').each(function (i, obj) {
var ele = [];
$(obj).find('.sample').each (function (i, obj) {
val = $(this).val()
ele.push(val)
})
arr.push(ele)
})
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card">
<input type="hidden" class="sample" value="A">
</div>
The result you are getting is expected.
There are many ways to achieve what you want: "I was expecting arr[A, B] and arr[A]"
But for me, I would go for adding more distinctions in your classes:
card-0, card-1, and so on should be coded by you
html
<div class="card-0 cards">
<input type="hidden" class="sample" value="A">
<input type="hidden" class="sample" value="B">
</div>
<div class="card-1 cards">
<input type="hidden" class="sample" value="A">
</div>
js
var mainArray = [];
var cardsCount = $('.cards').length;
for (var i1 = 0; i1 < cardsCount; i1++) {
var arr = [];
$(".card-" + i1 + " :input").each(
function() {
arr.push($(this).val());
}
);
mainArray.push(arr);
}
alert(mainArray[0]);
alert(mainArray[1]);

How to concatenate form array inputs before submission?

Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>

How can I produce an alert if three out of nine checkboxes are checked?

I have nine checkboxes linked to nine images and three of them use the name 'correct' using the code shown below.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"/>
</div>
The remaining six are unnamed using the code shown below.
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4"/>
</div>
I currently have the following code to produce an alert if the three checkboxes with the name "correct" are checked but it isn't working.
<script>
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
</script>
Can anyone help me with this?
Loop over all of the checkboxes, checking their state. Once this is done, create a variable "correct" and initialize it to true. Then go to each state in the variable and, if you find that its name isn't "correct" and it is checked or its name is "correct" and it isn't correct, set the variable to false. Then check if the variable is true and, if it is, display the alert.
View an example here: https://repl.it/GxsE/9
Using ES6:
const correctInputs = [...document.querySelectorAll('input[name="correct"]')];
const alertIfThree = () => {
const checkedCorrectInputs = correctInputs.filter(input => input.checked);
if (checkedCorrectInputs.length > 2) {
alert('Alert');
}
};
correctInputs.forEach(input => input.addEventListener('click', alertIfThree));
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
document.querySelectorAll('input[name="correct"]') gets all inputs with name "correct".
[...CODE] is spread operator, it converts code from previous point to array.
correctInputs.forEach(input => input.addEventListener('click', alertIfThree)) adds click event listener to each of them. That event listener is function alertIfThree().
alertIfThree() filters out those input elements that are not checked and produces alert if there are more than 2 of them.
EDIT
In response to your comment:
// jshint esnext: true
const inputs = [...document.querySelectorAll('input[name="correct"], input[name="incorrect"]')];
const alertIfCorrect = () => {
const checkedInputs = inputs.filter(input => input.checked),
noIncorrectCheckedInputs = checkedInputs.find(input => input.name === 'incorrect') === undefined;
if (checkedInputs.length > 2 && noIncorrectCheckedInputs) {
alert('Alert');
}
};
inputs.forEach(input => input.addEventListener('click', alertIfCorrect));
<p>Correct:
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
</p>
<p>Incorrect:
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
</p>
const is ES6 constant. "The value of a constant cannot change through re-assignment, and it can't be redeclared".
[...CODE_HERE] is so called spread syntax. Here, it turns what it contains after ellipsis into an array. Other way to do it would be to use Array.from().
() => { and input => CODE_HERE are arrow functions. They are ES6's syntactic sugar for function declaration.
What stands before => are parameters. () stands for 0 parameters. If you wanted function that takes few parameters, those braces would need to have those few parameters inside them. For one parameter, parameter's name can replace braces altogether (like in second code in this bullet point).
What stands after => is either expression or group of statements. Statements are surrounded by curly brackets ({}). If you omit them, you are writing an expression that your function will return. For example input => input.checked is equivalent to function(input) { return input.checked; }.
filter() and find() are methods of array prototype. They respectively filter and search an array using condition defined in a function that is passed to them as a parameter. Read more by following those two links.
If you need something else explained, let me know. Those functions and structures here are pretty... fresh, so you can just not know them yet.
I put this in a JSfiddle and it works for me. I just wrapped your JS in a function and added an onclick event.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"onclick="validate()"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4" onclick="validate()"/>
</div>
<script type=text/javascript">
function validate()
{
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
}
</script>
It will require some javascript. You will need o check the checkboxes each time one changes. So to start with you will need to check your checkboxes, assuming they have an assigned class of 'chk'. This can be done with a querySelector.
Each time a checkbox changes, the function 'check_checkboxes()' is called. This function will see for each checkbox with name='correct' if it is checked and then increment 'count'
var checkboxes = document.querySelectorAll(".chk");
var correct = document.querySelectorAll("[name=correct]");
function check_checkbox() {
var count = 0;
[].forEach.call(correct, function(item) {
if (item.checked) {
count++;
}
});
if (count >= 3) {
alert("count of 3 or more");
}
}
[].forEach.call(checkboxes, function(item) {
item.addEventListener("change", function() {
check_checkbox();
}, false);
});
<div class="nine">
<label for="correct1"><img class="picture1" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
Check the loop. Use for (i = 0; i < correct.length; i++) { instead for (i = 0; i <= correct.length; i++) {
var i, correct = document.getElementsByName('correct');
var correct_answers = [];
function validate(){
correct_answers = [];
for (i = 0; i < correct.length; i++) {
var element = correct[i].getAttribute("id");
var checked = correct[i].checked;
correct_answers.push({element,checked});
}
}
function show(){
document.getElementById('results').innerHTML ="";
for(var e=0;e<correct_answers.length;e++){
var box = document.createElement('div');
box.innerHTML = correct_answers[e].element+ " " + correct_answers[e].checked+ "<br>";
document.getElementById('results').appendChild(box);
}
}
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct1" name="correct"/>
</div>
<div class="nine">
<label for="correct2"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct2" name="correct"/>
</div>
<div class="nine">
<label for="correct3"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct3" name="correct"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect4"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect5"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect6"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect7"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect8"/>
</div>
<button onclick="show();">show results</button>
<div id="results"></div>
Use document.querySelectorAll('input[name]=correct') in your code.

Categories

Resources