I am trying to get the intersection of two arrays when the user selects them but I don't know how to pass an entire array through an input value.
Here is my script:
var checkedValue = document.querySelector('.leaflet-control-layers-selector:checked').value;
result = _.intersection(checkedValue);
console.log(checkedValue);
document.getElementById("AllMuseums").value = AllMuseums;
document.getElementById("MPaid").value = MPaid;
document.getElementById("MFree").value = MFree;
document.getElementById("MResto").value = MResto;
Here are my inputs:
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="AllMuseums" checked><span>All Museums</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MPaid" value="MPaid"><span id="icons1">Paid Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MFree" value="MFree"><span id="icons2">Free Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MResto" value="MResto"><span id="icons3">Restaurants</span></div>
</label>
And here are my arrays:
var AllMuseums=[Naturhistoriska,Junibacken,ArkDes,Fjarilshuset,Tekniska,Polismuseet,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel,Moderna],
MPaid=[Junibacken,Fjarilshuset,Tekniska,Polismuseet,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel],
MFree=[Naturhistoriska,ArkDes,Moderna],
MResto=[Naturhistoriska,Junibacken,ArkDes,Fjarilshuset,Tekniska,Skansen,Bergrummet,Vikingaliv,Vasa,Nordiska,Nobel,Moderna],
So there is a solution : https://jsfiddle.net/ajxeyqo4
inputs :
first input tag add value
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="AllMuseums" value="AllMuseums" checked><span>All Museums</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MPaid" value="MPaid"><span id="icons1">Paid Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MFree" value="MFree"><span id="icons2">Free Admission</span></div>
</label>
<label>
<div><input type="checkbox" class="leaflet-control-layers-selector" id="MResto" value="MResto"><span id="icons3">Restaurants</span></div>
</label>
<button onclick='test()'>
test
</button>
And your scripts :
function test(){
var AllMuseums=['Naturhistoriska','Junibacken','ArkDes','Fjarilshuset','Tekniska','Polismuseet','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel','Moderna'],
MPaid=['Junibacken','Fjarilshuset','Tekniska','Polismuseet','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel'],
MFree=['Naturhistoriska','ArkDes','Moderna'],
MResto=['Naturhistoriska','Junibacken','ArkDes','Fjarilshuset','Tekniska','Skansen','Bergrummet','Vikingaliv','Vasa','Nordiska','Nobel','Moderna'];
var checkedValue = document.querySelectorAll('.leaflet-control-layers-selector:checked');
var a =[]
_.map(checkedValue, function(value) {
a.push(eval(value.value));
});
var result = _.intersection(...a);
console.log(JSON.stringify(result))
}
Related
I need to get the children of the Section block. Namely fields and rabiobuttons. Next, check them for fullness. How to do it. I tried to get through childNodes, children but nothing worked.
In this case, I want to get the context of the section block and check the fields
Such sections, I need to validate section by section and until the previous one is filled, I do not validate the next one.
const formStepTwo = document.getElementById("formStepTwo");
const Section = document.querySelectorAll(".Section");
formStepTwo.addEventListener("change", () => {
//console.log( Section.item(0))
let count = Array.from(Section).forEach((i) => {
let context = i.children;
context.item()
console.log( this.querySelectorAll(".input[type=radio]"))
//console.log(context.forEach());
});
});
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</div>
</form>
You can actually check for input fields by targeting 'label' since they directly wrap over the input tag. Targeting through .Section can get a bit tricky, but is doable.
Another alternative is to directly target input fields using querySelectorAll('input') and then check for their type.
I've added example of both in the code snippet :
const formStepTwo = document.getElementById("formStepTwo");
const labels = document.querySelectorAll("label");
formStepTwo.addEventListener("change", () => {
let count = Array.from(labels).forEach((i) => {
let children = i.children;
Array.from(children).forEach((node) => {
if(node.nodeName.toLowerCase() === 'input') {
switch(node.type) {
case 'number' : validateNumberField(node);
break;
case 'radio' : validateRadio(node);
break;
// add more cases as required
default:
console.log('add default');
}
}
});
});
});
// Can also be done by targeting input directly
const input = document.querySelectorAll('input');
formStepTwo.addEventListener("change", () => {
Array.from(input).forEach((node) => {
if(node.nodeName.toLowerCase() === 'input') {
switch(node.type) {
case 'number' : validateNumberField(node);
break;
case 'radio' : validateRadio(node);
break;
// add more cases as required
default:
console.log('add default');
}
}
});
});
function validateNumberField(node) {
console.log('validating number field');
// add your validation
}
function validateRadio(node) {
console.log('validation radio button');
// add your validation for radio
}
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</div>
</form>
Maybe this helps you:
const formStepTwo = document.getElementById("formStepTwo");
const sections = [...document.querySelectorAll(".Section")];
formStepTwo.addEventListener("input", () => {
sections.forEach(s=>{
const inps=[...s.querySelectorAll("input,select")].filter(el=>el.type!=="radio"||el.checked);
console.log(inps.map(el=>el.name+":"+el.value))
});
});
<form class="stepTwo-profile" id="formStepTwo">
<p class="stepTwo-profile-title">Демография</p>
<div class="Section">
<label for="age"
>Возраст пациента<input
type="number"
class="stepTwo-profile-item-textAge"
name="age"
min="0"
max="80"
maxlength="2"
id="age"
/></label>
<p class="stepTwo-profile-item-smTitle">Пол</p>
<label for="male">
<input type="radio" name="gender" id="male" value="male" />Мужской
<span class="stepTwo-profile-item-radionbtn"></span
></label>
<label for="female">
<input type="radio" name="gender" id="female" value="female" />Женский
<span class="stepTwo-profile-item-radionbtn"></span>
</label>
</div>
</form>
The script goes through all sections (currently there is only one ;-)) and collects all input values. (Radio buttons are only picked up if they are "checked".)
I am trying to make a Js to search & filter items in JSON
so I use many radio in the "form" , the result will be [X,X,X,X,X,X]
I will set 50tags x 3(choose), I can feel my function will be large.
What ways can I change my function to be simpler?
function myFunction() {
var elements1 = document.getElementsByName("chair"),
elements2 = document.getElementsByName("car"),
elements3 = document.getElementsByName("house"),
elements4 = document.getElementsByName("tree"),
elements5 = document.getElementsByName("flower"),
elements6 = document.getElementsByName("grass");
var i;
for (var a = "", i = elements1.length; i--;) {
if (elements1[i].checked) {
var a = elements1[i].value;
break;
}
};
for (var b = "", i = elements2.length; i--;) {
if (elements2[i].checked) {
var b = elements2[i].value;
break;
}
};
for (var c = "", i = elements3.length; i--;) {
if (elements3[i].checked) {
var c = elements3[i].value;
break;
}
};
for (var d = "", i = elements4.length; i--;) {
if (elements4[i].checked) {
var d = elements4[i].value;
break;
}
};
for (var e = "", i = elements5.length; i--;) {
if (elements5[i].checked) {
var e = elements5[i].value;
break;
}
};
for (var f = "", i = elements6.length; i--;) {
if (elements6[i].checked) {
var f = elements6[i].value;
break;
}
};
var o2 = document.getElementById("output2");
o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>
Give the form an id, and you can refer to it as an object.
function myFunction() {
var form = document.getElementById("myForm");
var parts = [
form.chair.value,
form.car.value,
form.house.value,
form.tree.value,
form.flower.value,
form.grass.value
];
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
And this is an even simpler solution using a FormData object. It supports an arbitrary number of named form fields without having to actually name them in the function:
function myFunction() {
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
var parts = Array.from(formData.values());
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
Use document.querySelector() to directly select the value of the checked radio button based on element names.
function myFunction() {
var chair = document.querySelector('input[name="chair"]:checked').value;
var car = document.querySelector('input[name="car"]:checked').value;
var house = document.querySelector('input[name="house"]:checked').value;
var tree = document.querySelector('input[name="tree"]:checked').value;
var flower = document.querySelector('input[name="flower"]:checked').value;
var grass = document.querySelector('input[name="grass"]:checked').value;
var o2 = document.getElementById("output2");
o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
o2.innerHTML = o2.value;
}
Use arrays!
function myFunction() {
var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
var elems = elem_ids.map(id => document.getElementById(id));
var elems_check_values = elems.map(el => {
// el is kind of an array so
for(var i = 0; i < el.length; ++i)
if(el[i].checked)
return el[i].value;
return undefined;
}).filter(value => value == undefined) // to filter undefined values;
var output = "[" + elems_check_values.join(",") + "]";
var o2 = document.getElementById("output2");
o2.innerHTML = output
}
Your issue can be generalized to: how can I aggregate values for all fields in a given form?
The solution is a function that can be merely as long as 5 lines, and work for any amount of inputs with any type. The DOM model for <form> elements provides named keys (eg, myform.inputName) which each have a value property. For radio buttons, eg myform.tree.value will automatically provide the value of the selected radio button.
With this knowledge, you can create a function with a simple signature that takes a form HTMLElement, and an array of field names for the values that you need, like below: (hit the search button for results, and feel free to change the radio buttons).
function getFormValues(form, fields) {
var result = [];
for (var i = 0; i < fields.length; i++) {
result.push(form[fields[i]].value);
}
return result;
}
document.getElementById('filter').addEventListener('click', function(e) {
var o2 = document.getElementById("output2");
o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>
The thing you need to do is break the code up into reusable chunks. So make a method to get the value. That will reduce a lot of code. After than, you should look at a way to reduce how many elements you need to list. Finally, find an easy way to fetch all the values.
So below is code that does this. It uses a helper method to get the elements, find the value. Than it uses an array to know what element groups to look for. And finally it uses map to iterate over the list so you do not have to code multiple function calls.
function getSelected (radioBtnGroup) {
// get the elements for the radio button group
var elms = document.getElementsByName(radioBtnGroup)
// loop over them
for(var i=0; i<elms.length; i++) {
// if checked, return value and exit loop
if (elms[i].checked) {
return elms[i].value
}
}
// if nothing is selected, return undefined
return undefined
}
// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']
// call when you want to get the values
function getValues () {
// use map to get the values of the rabio button groups.
// map passes the index value as the first argument.
// code is map(function(k){return getSelected(k)})
var results = groups.map(getSelected)
//displat the results
console.log(results);
}
document.querySelector('#btn').addEventListener('click', getValues);
<form>
<fieldset>
<legend>Item 1</legend>
<label><input type="radio" name="rb1" value="1-1"> One</label>
<label><input type="radio" name="rb1" value="1-2"> Two</label>
<label><input type="radio" name="rb1" value="1-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 2</legend>
<label><input type="radio" name="rb2" value="2-1"> One</label>
<label><input type="radio" name="rb2" value="2-2"> Two</label>
<label><input type="radio" name="rb2" value="2-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 3</legend>
<label><input type="radio" name="rb3" value="3-1"> One</label>
<label><input type="radio" name="rb3" value="3-2"> Two</label>
<label><input type="radio" name="rb3" value="3-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 4</legend>
<label><input type="radio" name="rb4" value="4-1"> One</label>
<label><input type="radio" name="rb4" value="4-2"> Two</label>
<label><input type="radio" name="rb4" value="4-3"> Three</label>
</fieldset>
<button type="button" id="btn">Get Results</button>
</form>
Personally I would not store the values in an array, I would use an object with key value pairs.
var results = groups.reduce(function (obj, name) {
obj[name] = getSelected(name)
return obj
}, {});
/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}
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.
I have a form in my app with several checkboxen. I want the result(value) of the checked checkedboxes saved into separate rows in the database, see below. The problem is that when saving, only the first one (Ma) is saved and the other ones not eventhough the are checked in the form. When MA is not checkend nothing happens at all... I use JqueryMobile/JavaScript/PhoneGap Build
Form:
<form name="test">
<label class="label_check" id="l1" for="ch1">Ma
<input class="custom" type="checkbox" name="checkgroup" id="ch1" value="Ma" />
</label>
<label class="label_check" id="l2" for="ch2">Di
<input class="custom" type="checkbox" name="checkgroup" id="ch2" value="Di" checked />
</label>
<label class="label_check" id="l3" for="ch3">Woe
<input class="custom" type="checkbox" name="checkgroup" id="ch3" value="Woe" />
</label>
<label class="label_check" id="l4" for="ch4">Do
<input class="custom" type="checkbox" name="checkgroup" id="ch4" value="Do" />
</label>
<label class="label_check" id="l5" for="ch5">Vr
<input class="custom" type="checkbox" name="checkgroup" id="ch5" value="Vr" checked />
</label>
<label class="label_check" id="l6" for="ch6">Za
<input class="custom" type="checkbox" name="checkgroup" id="ch6" value="Za" />
</label>
<label class="label_check" id="l7" for="ch7">Zo
<input class="custom" type="checkbox" name="checkgroup" id="ch7" value="Zo" />
</label>
</form>
</p>
<p>
<input type="button" name="saveData" id="btn1" value="Save" onclick="saveRecordSafety();"/>
Javascript:
function saveRecordSafety() {
//Write the record to the database
theDBbeter.transaction(insertRecordSafety, onTxErrorB, onTxSuccessB);
}
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.lenght; r++);
if (elementen[r].checked) {
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
I think the problem is because of your for loop being terminated by a semicolon:
for (var r= 0; r < elementen.lenght; r++);
Try this:
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.length; r++)
{
if (elementen[r].checked)
{
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
}
I've also spaced things out to make it easier to read.