how to get multiple text with same name? - javascript

when checkbox are checked for each checkbox jquery create input
How can I get all inputs with name??
if checkbox checked create input:
<script>
function dynInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
input.className = "cbox";
var div = document.createElement("div");
div.className = "cbox-div";
div.id = cbox.name;
div.innerHTML =cbox.name;
div.appendChild(input);
document.getElementById("insertinputs").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}</script>
checkbox and Inputs:
<form class="add-item">
<input type="checkbox" onclick="dynInput(this);" name="1"> 1<br>
<input type="checkbox" onclick="dynInput(this);" name="2"> 2<br>
<input type="checkbox" onclick="dynInput(this);" name="3"> 3<br>
<input type="checkbox" onclick="dynInput(this);" name="4"> 4<br>
</form>
<p id="insertinputs"></p>
I can only get first Input value :
var item = $(".cbox").val();
console.log(item);

You need to iterate over all the inputs like:
$(".cbox").each(function(){
var item = $(this).val();
console.log(item);
});

var item=[];
$(".cbox").each(function(){
item.push($(this).val());
});

var items = document.querySelectorAll('.cbox');
var values = [];
items.forEach(function(item) {
values.push(item.value);
});
console.log(values);

because as the documentation states for val() it only returns the first item in the collection. You would need to loop over the collection and read each item's value.
So you need to loop over the collection and build up the list. You can do it with each() or map()
var vals1 = [];
$('[type="checkbox"]').each( function () {
vals1.push(this.value);
});
var vals2 = $('[type="checkbox"]').map( function () {
return this.value;
}).get();
console.log("vals1", vals1.join(","))
console.log("vals2", vals2.join(","))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="a"> 1<br>
<input type="checkbox" value="b"> 2<br>

Related

Check all/sum values - how to put span inside input

I wrote some code which sums up all the values of checkboxes with a "toggle all" option. At the beginning I needed to only have information about the value, but now I need to have sum inside an input element, but it does not work.
NOTICE: I know ID can be used only once! I put both input and span to show that it works with span and not with input.
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total')
function sumUpdate() {
totalElement.innerHTML = inputs.reduce(function(result, input) {
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(2);
}
// Update the sums in function on input change.
inputs.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/></div> <br/> Price: <span id="payment-total">0</span>
</div>
I done some modification to your sumUpdate function making it working now, you need to give the input control and the span different id:
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var values = document.querySelectorAll('.sum');
function sumUpdate() {
var total = 0;
var selectedItems = Array.prototype.filter.call(values,function(input) {
return input.checked ? input : null;
});
$(selectedItems).each(function (index, element) {
total = total + parseFloat($(element).val());
});
total = parseFloat(total).toFixed(2);
$('#payment-total').val(total);
$('#payment-total-span').text(total);
}
// Update the sums in function on input change.
values.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/> <br/> Price: <span id="payment-total-span">0</span>
</div>

How to add string value of checkbox by using this.name to same array using JQuery

My problem is that I want to add the value of input-checkbox. This code is adding the value but not to the same array
$(".ticketAddition").change(function (){
var name = [];
name.toString();
if (this.checked) {
name.push(this.name);
console.log(name);
}
});
You can loop over all the checked items to account for checking and unchecking alike:
$(".ticketAddition").change(function (){
var ticketSelection = [];
$('.ticketAddition:checked').each(function() {
ticketSelection.push(this.getAttribute('name'));
});
document.querySelector('#result').innerText = JSON.stringify(ticketSelection);
// or console.log(ticketSelection)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li><label><input type="checkbox" name="ticket_1" class="ticketAddition" /> Ticket #1</label></li>
<li><label><input type="checkbox" name="ticket_2" class="ticketAddition" /> Ticket #2</label></li>
<li><label><input type="checkbox" name="ticket_3" class="ticketAddition" /> Ticket #3</label></li>
</ul>
Checked tickets: <span id="result"></span>
Try this:
var name = [];
$(".ticketAddition").change(function (){
name.toString(); // Why ?
if (this.checked) {
name.push(this.name);
console.log(name);
} else {
name.splice(name.indexOf(this.name), 1);
}
});
You can select all the checked checkbox using :checked selector. Use map() and get() to loop thru the checkboxes.
$(".ticketAddition").change(function() {
var names = $(".ticketAddition:checked").map(function() {
return this.name;
}).get();
console.log(names)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="ticketAddition" name="apple" value="apple"> apple<br>
<input type="checkbox" class="ticketAddition" name="orange" value="orange"> orange<br>
<input type="checkbox" class="ticketAddition" name="pear" value="pear"> pear<br>
You could instead get checked checkboxes inside your .tickedAddition element, where you map each element selected using $(":checkbox:checked", this) to its value attribute:
$(".ticketAddition").change(function() {
let names = $(":checkbox:checked", this).get().map(({value}) => value);
console.log(names);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="ticketAddition">
<label for="first">Frog</label>
<input type="checkbox" id="frog" name="cb" value="frog"/>
<label for="first">Emu</label>
<input type="checkbox" id="emy" name="cb" value="emu"/>
<label for="first">Bird</label>
<input type="checkbox" id="bird" name="cb" value="bird"/>
</form>

Javascript check / uncheck checkboxes based on id

I have many server input checkboxes. I have given the first checkbox the id all. By default it will be checked. When the user checks other checkboxes, then checkbox with id all will be unchecked. And if all is checked other checkboxes will be unchecked. For this to happen i made the code but nothing is happening.
Here is what i have tried.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check()" checked/>ALL <br/>
<input type="checkbox" id="servers" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" id="servers" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" id="servers" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" id="servers" value="amp" name="server[]" onChange="check()" />AMP <br/>
</form>
function check(){
var all = document.getElementById("all"),
group = document.getElementById("servers");
if(all.checked == true){
group.checked == false;
}elseif(group.checked == true){
all.checked == false;
}
}
I wanted my code to work like THIS.
I dont want to use jQuery for some reasons. So i need my code to be in pure JS.
Any help will be appreciated.
You can't use the same ID on multiple elements.
Try this, notice how I placed the checkboxes in a div
Here it is working: http://jsfiddle.net/Sa2d3/
HTML:
<form>
<div id="checkboxes">
<input type="checkbox" id="all" value="all" name="all" onChange="check()" />ALL <br/>
<input type="checkbox" value="xampp" name="server[]" onChange="check()" />XAMPP <br/>
<input type="checkbox" value="wamp" name="server[]" onChange="check()" />WAMP <br/>
<input type="checkbox" value="mamp" name="server[]" onChange="check()" />MAMP <br/>
<input type="checkbox" value="amp" name="server[]" onChange="check()" />AMP <br/>
</div>
</form>
JavaScript:
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// loop through all the inputs, skipping the first one
for (var i = 1, input; input = inputs[i++]; ) {
// Set each input's value to 'all'.
input.checked = el.checked;
}
}
// We need to check if all checkboxes have been checked
else {
var numChecked = 0;
for (var i = 1, input; input = inputs[i++]; ) {
if (input.checked) {
numChecked++;
}
}
// If all checkboxes have been checked, then check 'all' as well
inputs[0].checked = numChecked === inputs.length - 1;
}
}, false);
EDIT:
Based on your request in the comment here is the updated javascript:
http://jsfiddle.net/T5Pm7/
document.getElementById('checkboxes').addEventListener('change', function(e) {
var el = e.target;
var inputs = document.getElementById('checkboxes').getElementsByTagName('input');
// If 'all' was clicked
if (el.id === 'all') {
// If 'all' is checked
if (el.checked) {
// Loop through the other inputs and removed the check
for (var i = 1, input; input = inputs[i++]; ) {
input.checked = false;
}
}
}
// If another has been clicked, remove the check from 'all'
else {
inputs[0].checked = false;
}
}, false);
You can only assign the same id to one element. What you want to do is give them a class="servers" and then use document.getElementsByClassName("servers"); in your JavaScript.
You cannot have same id for multiple HTML elements. You could do something like this to achieve what you are asking for.
<form>
<input type="checkbox" id="all" value="all" name="all" onChange="check(this, 'a')" checked/>ALL <br/>
<input type="checkbox" id="servers1" value="xampp" name="server[]" onChange="check(this, 's')" />XAMPP <br/>
<input type="checkbox" id="servers2" value="wamp" name="server[]" onChange="check(this, 's')" />WAMP <br/>
<input type="checkbox" id="servers3" value="mamp" name="server[]" onChange="check(this, 's')" />MAMP <br/>
<input type="checkbox" id="servers4" value="amp" name="server[]" onChange="check(this, 's')" />AMP <br/>
</form>
<script>
function check(cb, type){
var all = document.getElementById("all");
if (type == "a" && cb.checked){
var els = document.getElementsByName("server[]");
for(var i = 0; i < els.length; ++i)
els[i].checked = false;
} else if( type == "s" && cb.checked) {
all.checked = false;
}
}
</script>
put this function
function jvcheck(id,Vale){
Checkboxesclass = '.group'+id;
$(Checkboxesclass).each(function() {
this.checked = Vale;
});
}
and then put this code in your main checkbox
jvcheck('group222',this.checked);
all checkbox with class group222 now checked .

Add the sum of from the value select of radiobutton

For instance, radiobutton one = value 1, radiobutton two = value 2.
Here is the code I have:
Script file:
<script type="text/javascript">
$(document).ready(function () {
$("div[data-role='footer']").prepend('Back');
$(".Next").click(function () {
$.mobile.changePage("#" + $("#Answer").val());
});
$("input[type=radio]").click(function () {
var answer = $(this).val();
$("#Answer").val(answer);
});
$('.Answer').live("click", function () {
var NextQuestionID = $(this).attr('NextQuestionId');
if (NextQuestionID == '') {
location.href = "/Surveys/Index";
}
$("#survey").load('/Questions/GetQuestion', { Id: NextQuestionID }, function () {
$('#answerInput').textinput();
$(".Answer").button();
});
});
});
and here is my markup:
<input type="radio" name="Answer" id="radio-choice-1" value="Question2" />
<input id="Answer" class="Answer" type="hidden" value="first" />
<div class="innerspacer">
Next
</div>
How do I assign the radio button as value from 1 to 4 and sum up the value for all the question?
There is a lot going on in your question and it is unclear what you want. I'm taking a guess and assuming you have a say 5 radio buttons and you want the 5th radio button value to be the sum of the other 4 values. Is that correct?
Here is an example of doing that: jsfiddle
HTML:
<div id="container">
<label>
<input type="radio" name="something" value="1">
A?
</label>
<label>
<input type="radio" name="something" value="3">
B?
</label>
<label>
<input type="radio" name="something" value="5">
C?
</label>
<label>
<input type="radio" name="something" value="">
All?
</label>
</div>
JavaScript:
$(document).ready(function() {
var choices = $('input[name="something"]');
var total = 0;
choices.each(function() {
var choice = $(this);
var value = parseInt(choice.val(), 10);
if (!isNaN(value)) {
total += value;
}
});
choices.filter(':last').val(total);
});
You will need to adapt this to your HTML.

Getting all selected checkboxes in an array

So I have these checkboxes:
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.
My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.
Any thoughts?
Edit: I would only want the selected checkboxes to be added to the array
Formatted :
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Hopefully, it will work.
Pure JS
For those who don't want to use jQuery
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;
for(k=0;k< chklength;k++)
{
chk_arr[k].checked = false;
}
I didnt test it but it should work
<script type="text/javascript">
var selected = new Array();
$(document).ready(function() {
$("input:checkbox[name=type]:checked").each(function() {
selected.push($(this).val());
});
});
</script>
Pure JavaScript with no need for temporary variables:
Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
ES6 version:
const values = Array
.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
function getCheckedValues() {
return Array.from(document.querySelectorAll('input[type="checkbox"]'))
.filter((checkbox) => checkbox.checked)
.map((checkbox) => checkbox.value);
}
const resultEl = document.getElementById('result');
document.getElementById('showResult').addEventListener('click', () => {
resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5
<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>
This should do the trick:
$('input:checked');
I don't think you've got other elements that can be checked, but if you do, you'd have to make it more specific:
$('input:checkbox:checked');
$('input:checkbox').filter(':checked');
In MooTools 1.3 (latest at the time of writing):
var array = [];
$$("input[type=checkbox]:checked").each(function(i){
array.push( i.value );
});
If you want to use a vanilla JS, you can do it similarly to a #zahid-ullah, but avoiding a loop:
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
The same code in ES6 looks a way better:
var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
display: block;
}
<label>
<input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
<input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
<input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
<input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>
In Javascript it would be like this (Demo Link):
// get selected checkboxes
function getSelectedChbox(frm) {
var selchbox = [];// array that will store the value of selected checkboxes
// gets all the input tags in frm, and their number
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
return this.value;
}).get();
Another way of doing this with vanilla JS in modern browsers (no IE support, and sadly no iOS Safari support at the time of writing) is with FormData.getAll():
var formdata = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question
// allchecked is ["1","3","4","5"] -- if indeed all are checked
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {
var values = 0.00;
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values=values+parseFloat(($(this).val()));
// }
});
console.log( parseFloat(values));
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4.00" />
<input type="checkbox" name="type" value="3.75" />
<input type="checkbox" name="type" value="1.25" />
<input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Array.from($(".yourclassname:checked"), a => a.value);
Select Checkbox by input name
var category_id = [];
$.each($("input[name='yourClass[]']:checked"), function(){
category_id.push($(this).val());
});
Using Jquery
You only need to add class to every input, i have add class "source" you can change it of course
<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />
<script type="text/javascript">
$(document).ready(function() {
var selected_value = []; // initialize empty array
$(".source:checked").each(function(){
selected_value.push($(this).val());
});
console.log(selected_value); //Press F12 to see all selected values
});
</script>
function selectedValues(ele){
var arr = [];
for(var i = 0; i < ele.length; i++){
if(ele[i].type == 'checkbox' && ele[i].checked){
arr.push(ele[i].value);
}
}
return arr;
}
var array = []
$("input:checkbox[name=type]:checked").each(function(){
array.push($(this).val());
});
can use this function that I created
function getCheckBoxArrayValue(nameInput){
let valores = [];
let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
checked.forEach(input => {
let valor = input?.defaultValue || input?.value;
valores.push(valor);
});
return(valores);
}
to use it just call it that way
getCheckBoxArrayValue("type");
Use below code to get all checked values
var yourArray=[];
$("input[name='ordercheckbox']:checked").each(function(){
yourArray.push($(this).val());
});
console.log(yourArray);
var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
return this.value;
}).get();
Use commented if block to prevent add values which has already in array if you use button click or something to run the insertion
$('#myDiv').change(function() {
var values = [];
{
$('#myDiv :checked').each(function() {
//if(values.indexOf($(this).val()) === -1){
values.push($(this).val());
// }
});
console.log(values);
}
});
<div id="myDiv">
<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
You could try something like this:
$('input[type="checkbox"]').change(function(){
var checkedValue = $('input:checkbox:checked').map(function(){
return this.value;
}).get();
alert(checkedValue); //display selected checkbox value
})
Here
$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function() looping on all checkbox,
here is my code for the same problem someone can also try this.
jquery
<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];
$.each($("input[name='check1']:checked"), function(){
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>
var idsComenzi = [];
$('input:checked').each(function(){
idsComenzi.push($(this).val());
});
Just adding my two cents, in case it helps someone :
const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);
I already had a jQuery object, so I wouldn't select all my checkbox another time, that's why I used jQuery's filter method. Then I convert it to a JS array, and I map the array to return items'value.
This is an old question but in 2022 There is a better way to implement it using vanilla JS
We don't need react or fancy frameworks.
We just need handle two onchange events like this:
const types = [{id:1, name:'1'}, {id:2, name:'2'}, {id:3, name:'3'}, {id:4, name:'4'}, {id:5, name:'5'}, {id:6, name:'6'}]
const all = document.getElementById('select-all')
const summary = document.querySelector('p')
let selected = new Set()
const onCheck = event => {
event.target.checked ? selected.add(event.target.value) : selected.delete(event.target.value)
summary.textContent = `[${[...selected].join(', ')} | size: ${selected.size}] types selected.`
all.checked = selected.size === types.length
}
const createCBInput = t => {
const ol = document.querySelector('ol')
const li = document.createElement('li')
const input = document.createElement('input')
input.type = 'checkbox'
input.id = t.id
input.name = 'type'
input.value = t.id
input.checked = selected.has(t.id)
input.onchange = onCheck
const label = document.createElement('label')
label.htmlFor = t.id
label.textContent = t.name
li.append(input, label)
ol.appendChild(li)
}
const onSelectAll = event => {
const checked = event.target.checked
for (const t of types) {
const cb = document.getElementById(t.id)
cb.checked = checked ? true : selected.has(t.id)
const event = new Event('change')
cb.dispatchEvent(event)
}
}
all.checked = selected.size === types.length
all.onchange = onSelectAll
for (const t of types) {
createCBInput(t)
}
ol {
list-style-type: none;
padding-left: 0;
}
<ol>
<li>
<input type="checkbox" id="select-all">
<label for="select-all"><strong>Select all</strong></label>
</li>
</ol>
<p></p>
$(document).ready(function()
{
$('input[type="checkbox"]').click(function() {
var arr =[];
$('input[type="checkbox"]:checked').each(function() {
//arr.push($(this).parent('p').text()+'\n');
arr.push($(this).val()+'\n');
});
var array = arr.toString().split(',')
$("#text").val(array.join(""));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Append value when checkbox is checked</p>
<textarea rows="4" id="text" style="width: 100%">
</textarea>
<div id="checkboxes">
<p><input type="checkbox" value="Item 1"><span> Item 1</span></p>
<p><input type="checkbox" value="Item 2"><span> Item 2</span></p>
<p><input type="checkbox" value="Item 3"><span> Item 3</span></p>
<p><input type="checkbox" value="Item 4"><span> Item 4</span></p>
<p><input type="checkbox" value="Item 5"><span> Item 5</span></p>
</div>

Categories

Resources