Just wondering if anyone can help. I currently have code like this:
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Each 'section' is dynamically produced. How do I go about inserting the value of each input into the span of each section when checked. I have been playing around with Arrays but stumbling due to each section being produced dynamically.
Can any of you help me out?
Better give each checkbox input a value, anyway, I'll use id instead.
// Listen to all checkboxes
$('section input[type="checkbox"]').click(function(e) {
var $this = $(e.target);
// Find the container of same group.
var $parent = $this.parent('section');
// Find all checked ones.
var checked = $parent.find('input[type="checkbox"]:checked');
// Map the value or id, to an array.
var result = $.map(checked, function(ele) {
return $(ele).attr('id');
});
// Get the result, use it whatever you want.
$parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<span class="tags"></span>
<label for="shoes">Shoes</label>
<input type="checkbox" id="shoes">
<label for="jeans">Jeans</label>
<input type="checkbox" id="jeans">
<label for="tops">Tops</label>
<input type="checkbox" id="tops">
</section>
<section>
<span class="tags"></span>
<label for="monkey">monkey</label>
<input type="checkbox" id="monkey">
<label for="lion">lion</label>
<input type="checkbox" id="lion">
<label for="dog">dog</label>
<input type="checkbox" id="dog">
</section>
Use this javascript:
<script type="text/javascript">
window.addEventListener("load",function(){
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++){
var n = 0;
sections[i].span = sections[i].getElementsByTagName("span")[0];
sections[i].checkboxes = [];
var inputs = sections[i].getElementsByTagName("input");
for(var c=0; c<inputs.length; c++){
if(inputs[c].type!="checkbox"){continue}
sections[i].checkboxes[n++]=inputs[c];
inputs[c].onchange=function(){this.parentNode.getValues();}
}
sections[i].getValues = function(){
var o=[], n=0;
for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id;}}
this.span.innerHTML = o.join(", ");
};
}
},false);
</script>
Related
In short, if a user selects yes to a radio option, I'm trying to obtain the data-name attribute from that input and push it to an array called accepted_array.
If a user selects no, then store data-name to declined_array.
Here is a visual to the markup:
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
Here are 2 approaches I've experimented with:
First approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var checkedVal = $this.val();
var accepted_array = [];
var declined_array = [];
if( checkedVal == "yes" ) {
var name = $this.data("name");
accepted_array.push(name);
} else {
declined_array.push(name);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + accepted_array.join(","));
});
});
}) (jQuery);
This only executes for the selected user and adds the name to both arrays.
Second approache.
(function ($) {
$( ".guest__attendance-input" ).each(function(index) {
$(this).on("click", function(){
var $this = $(this);
var data = [];
var checked = $this.is(':checked');
var name = $this.attr('data-name');
if (checked) {
if (!data[name]) {
data[name] = []
}
data[name].push($this.val())
}
console.log(data);
});
});
}) (jQuery);
Which only adds the user to a single array.
If both select yes, I need both names in the accepted_array. If someone selects yes initially and then selects no I need to remove them from the accepted_array and vice versa.
You can use splice with inArray to remove value from array if someone selects yes initially and then selects no and vice versa.
Example:
var accepted_array = [];
var declined_array = [];
$('.guest__options-group > input[type=radio]').on('change', function() {
var $this = $(this);
var name = $this.data("name");
var checkedVal = $this.val();
var name = $this.data("name");
if (checkedVal == "yes") {
accepted_array.push(name);
declined_array.splice($.inArray(name, declined_array), 1);
} else {
declined_array.push(name);
accepted_array.splice($.inArray(name, accepted_array), 1);
}
console.log("accepted " + accepted_array.join(","));
console.log("declined " + declined_array.join(","));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- options for John -->
<div class="guest__options-group">
<input id="attending-yes-0" type="radio" name="attendance-0" value="yes" data-name="John" required />
<label for="attending-yes-0">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-0" type="radio" name="attendance-0" value="no" data-name="John" required />
<label for="attending-no-0">No</label>
</div>
<!-- options for Alex -->
<div class="guest__options-group">
<input id="attending-yes-1" type="radio" name="attendance-1" value="yes" data-name="Alex" required />
<label for="attending-yes-1">Yes</label>
</div>
<div class="guest__options-group">
<input id="attending-no-1" type="radio" name="attendance-1" value="no" data-name="Alex" required />
<label for="attending-no-1">No</label>
</div>
I have 3 input checkboxes. Each of them displays a div if checked. Because the three has the same JS I have decided to have just one JS including 3 variables (one per input) but it is not working. Before I had three independent JS and it worked fine.
CODE
document.getElementById()
var cb1 = document.getElementById('checkbox1'); checkbox1.onchange = {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
};
var cb2 = document.getElementById('checkbox2'); checkbox2.onchange = {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
};
var cb3 = document.getElementById('checkbox3'); checkbox3.onchange = {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3"> Course 3
</label>
</form>
<br>
<div id ="course1">
Text course 1
</div>
<br>
<div id ="course2">
Text course 2
</div>
<br>
<div id ="course3">
Text course 3
</div>
Fiddle: https://codepen.io/antonioagar1/pen/YOwBeE?editors=1010
After fixing your syntax errors (identation is very imporant, if it was correct in your code you would had see that you have many if statements not closing correclty)
Well, besides those errors, I managed a way to you that you only need a single function to achieve your desired result.
If you see in the HTML part, you'll note that I added some new attributes to checkboxes and divs, called data-idCheck, where the checkbox with data-idCheck will display the div whose have that same attribute.
Check below to see if my code helps you.
var cb1 = document.getElementById('checkbox1');
cb1.onchange = checkChecked;
var cb2 = document.getElementById('checkbox2');
cb2.onchange = checkChecked;
var cb3 = document.getElementById('checkbox3');
cb3.onchange = checkChecked;
function checkChecked(){
let idCheck = this.getAttribute("data-idCheck");
let relatedDiv = document.querySelector("div[data-idCheck='" + idCheck + "']");
if (this.checked) {
relatedDiv.style.display = 'block';
} else {
relatedDiv.style.display = 'none';
}
}
.hiddenDiv{
display: none;
}
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" data-idCheck="1"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" data-idCheck="2"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" data-idCheck="3"> Course 3
</label>
</form>
<br>
<div id ="course1" class="hiddenDiv" data-idCheck="1">
Text course 1
</div>
<br>
<div id ="course2" class="hiddenDiv" data-idCheck="2">
Text course 2
</div>
<br>
<div id ="course3" class="hiddenDiv" data-idCheck="3">
Text course 3
</div>
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 would like to add checked checkbox values as url parameter to my link.
This is what I have amongst others:
<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1"></label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1"></label>
<script>
$(".checkbox").on("change", function() {
var values = [];
$('.checkbox:checked').each(function() {
var result = $(this).val();
values.push(result);
});
var key = $(".link").html(values.join("&"));
document.write('Open here');
});
</script>
The expected result is "http://www.example.com/test.html?bx1=1&bx2=1".
I hope someone can help me with this.
Thanks for these lines:
<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1"></label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1"></label>
<a class="link" href="http://www.example.com/test.html">Open here</a>
<script>
$(".checkbox").on("change", function() {
console.log('fzef');
var values = [];
$('.checkbox:checked').each(function() {
var result = $(this).val();
values.push(result);
});
$(".link").attr('href', 'http://www.example.com/test.html?' + values.join("&"));
});
// Init link on page load
$(".checkbox").trigger("change");
</script>
I get a &on& between my values and it does not work on IE. Any idea? Thanks!
You can do like this:
<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1"></label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1"></label>
<a class="link" href="http://www.example.com/test.html">Open here</a>
<script>
$(".checkbox").on("change", function() {console.log('fzef');
var values = [];
$('.checkbox:checked').each(function() {
var result = $(this).val();
values.push(result);
});
$(".link").attr('href', 'http://www.example.com/test.html?' + values.join("&"));
});
// Init link on page load
$(".checkbox").trigger("change");
</script>
Wrap the checkboxes in a form, give them names and let jQuery do the work with .serialize():
$(function() {
$("form").on("change", function() {
var href = "http://www.example.com/test.html",
params = $(this).serialize();
if (params.length > 0) {
href += "?" + params;
}
console.log(href);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="box1" name="bx1" type="checkbox" class="checkbox" value="1" />bx1
<input id="box2" name="bx2" type="checkbox" class="checkbox" value="1" />bx2
</form>
The correction you need to do is in the line
var key = $(".link").html(values.join("&"));
You need to change it to
var key = values.join("&");
Why?
Because there is no .link selector in your code.
try like this:
you need with document.write()
document.write('http://www.example.com/test.html?' + values.join('&')+'');
OR
$("button").on("click", function() {
var values = [];
$('.checkbox:checked').each(function() {
var result = $(this).val();
values.push(result);
});
$('#url').attr('href','http://www.example.com/test.html?' + values.join('&') );
$('#url').html('http://www.example.com/test.html?' + values.join('&'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1">first</label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1">second</label>
<button >Go</button>
<a id="url"></a>
I have multiple checkboxes
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
</div>
How to find all checked checkboxes and create json or array with result of checking?
In case you just want to use pure/vanilla JS, here is an example:
HTML HEAD
<script type="text/javascript">
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}
</script>
HTML BODY
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
<input type="button" onclick="alert(getCheckedCheckboxesFor('employee'));" value="Get Values" />
</div>
JS Fiddle link: http://jsfiddle.net/dY372/
Try this:
Fiddle
jQuery:
var selected = [];
$('.data input:checked').each(function() {
selected.push($(this).val());
});
Javascript:
var checkboxes = document.getElementsByName('employee');
var selected = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
selected.push(checkboxes[i].value);
}
}
Using querySelectorAll:
var checked = document.querySelectorAll('[name="employee"]:checked');
Support: IE9+.
var elements=document.getElementsByName('employee');
should return you an array of the elements you require
DEMO
function checked(){
var items=getElementsByname('checkbox');
var selectedlist=[];
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedlist+=items[i].value+"\n";
}
alert(selectedlist);
}