I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>
I have below options, I want to use 1,2,3 options as radio button.
[checkbox] option 1 : $100
[checkbox] option 2 : $200
[checkbox] option 3 : $300
[checkbox] Registration fee : $50
Total = Option + Registration fee;
After selecting check box, value should be added into total and after unchecking, value should be deductefromtotal`. but the challenge is I want to use option 1,2 and 3 as radio buttons (only one option should be selected one time). But if I am using standard radio buttons for options then value is including in total on select but not deducting old options value from total if i select new option.
I used this code
<script type="text/javascript">
var total = 0;
function fee(item) {
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total + "";
}
</script>
HTML
<input id="checkbox1" type="checkbox" name="program1" value="100" onClick="fee(this);"/>
<input id="checkbox2" type="checkbox" name="program2" value="200" onClick="fee(this);"/>
<input id="checkbox3" type="checkbox" name="program3" value="300" onClick="fee(this);"/>
<input id="checkbox4" type="checkbox" name="fee" value="50" onClick="fee(this);"/>
I assume you need at least one of them.
Radios will uncheck if they have the same name:
function calc() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg"),
total = document.getElementById("total"),
tot = 0;
for (var i=0;i<rads.length;i++) {
tot+=rads[i].checked?parseInt(rads[i].value,10):0;
}
if (reg.checked) tot += parseInt(reg.value,10);
total.value=tot;
}
window.onload=function() {
var rads = document.getElementsByName("option"),
reg = document.getElementById("reg");
for (var i=0;i<rads.length;i++) {
rads[i].onclick=calc;
}
reg.onclick=calc;
}
<input type="radio" name="option" id="option1" value="100" />100
<input type="radio" name="option" id="option2" value="200" />200
<input type="radio" name="option" id="option3" value="300" />300 <br/>
<input type="checkbox" name="reg" id="reg" value="50" />50<br/>
Total <input type="text" readonly id="total" /><br/>
The name and concept of "radio button" comes from the old car radios where pressing one button would make the other button reset:
I don't want to discuss about how your design is probably wrong.
But I like to introduce a solution that does not imply some javascript to disable all checkbox and only allow one to be selected.
By changing the style of a radio button to look like a checkbox, you can easily achieve what you are asking.
form > input[type="radio"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
}
<form>
<input type="radio" name="program" value="100" /> program1<br />
<input type="radio" name="program" value="200" /> program2<br />
<input type="radio" name="program" value="300" /> program3<br />
<input type="checkbox" name="fee" value="50" /> fee
</form>
You SHOULD not use this and think of using some radio button. This is counter intuitive for users.
try this:
function fee(ev) {
var total = 0;
var item = ev.target;
if (item.checked) {
total += parseInt(item.value);
} else {
total -= parseInt(item.value);
}
// alert(total);
document.getElementById('Totalcost').innerHTML = total;
}
document.querySelector('form').addEventListener('change', fee);
<div id='Totalcost'>0000</div>
<form>
<input type="radio" name='name' value="100">option1(100£)
<br>
<input type="radio" name='name' value="200">option2(200£)
<br>
</form>
using form and change event the code is more concise
Personally I would use a simple MVVM library for this, Vue.js is a rather simple example.
This way you don't have to use your DOM as a datastore and both your presentation and your logic are separated rather clearly.
var v = new Vue({
el: 'body',
data: {
checkboxes: [{
name: 'first',
value: 100,
checked: false
}, {
name: 'second',
value: 200,
checked: false
}, {
name: 'third',
value: 300,
checked: false
}],
optional: {
name: 'optional',
value: 50,
checked: false
}
},
methods: {
foo: function() {
var sum = this.checkboxes.reduce(function(sum, item) {
return sum + (item.checked ? item.value : 0);
}, 0);
sum += this.optional.checked ? this.optional.value : 0;
return sum;
},
bar: function(e) {
if (e.targetVM.checked) {
this.checkboxes.forEach(function(checkbox) {
checkbox.checked = false;
});
e.targetVM.checked = true;
}
}
}
});
ul {
list-style: none;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.12/vue.min.js"></script>
<ul>
<li v-repeat="checkboxes">
<input type="checkbox" id="checkbox_{{name}}" v-model="checked" v-on="click: bar" />
<label for="checkbox_{{name}}">{{name}}: {{value}}</label>
</li>
</ul>
<input type="checkbox" v-model="optional.checked" id="optional_{{optional.name}}" />
<label for="optional_{{optional.name}}">{{optional.name}}</label>
<p>Total: <span v-text="foo()"></span>
</p>
I think this is pretty straight forward.
$(".total").html("$" + (parseInt($(this).val()) + 500));
Made a small fiddle for you here.
Try something like below, would require a lot of clean up.
$(document).ready(function() {
//set initial state.
var fee= 50;
$('#val1').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val1').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val2').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val2').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
$('#val3').change(function() {
if($(this).is(":checked")) {
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) + parseInt(returnVal);
alert(fee);
} else {
alert('unchecked');
var returnVal = $('#val3').val();
alert(returnVal);
fee = parseInt(fee) - parseInt(returnVal);
alert(fee);
}
});
});
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.
if user inputs a value in the input field the class value on the checkbox will change automatically
input field:
<input style="width:25px; margin-left:5px;" type="text" name="qtyA" id="qtyA" />
checkbox:
<input id="INsrv1" name="INopt" type="checkbox" value="1" />1<br>
<input id="INsrv2" name="INopt" type="checkbox" value="2" />2<br>
<input id="INsrv3" name="INopt" type="checkbox" value="3" />3<br>
<input id="INsrv4" name="INopt" type="checkbox" value="4" />4<br>
javascript:
<script>
$(document).ready(function() {
$('#qtyA').on('change', function() {
var max = $(this).val();
});
$("[name$='INopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
});
</script>
for ex:
the user inputs 3 in input field "qtyA"
value : 3
the maxCheckbox[] value on the script will change along with it
from maxCheckbox[1] to maxCheckbox[3]
the actual code:
<script>
$(document).ready(function() {
$('#qtyA').on('change', function() {
var max = $(this).val();
alert(max);
});
$("#srv").on('change', function() {
var max = $('#qtyA').val();
alert(max);
var selVal = $(this).val();
if (selVal == 'Inbound') { // Inbound
$('.Inbound').show();
$('.Outbound').hide();
$("[name$='OUTopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$("[name$='INopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
$('#valOUT').val('');
$('div#Outbound').find('span').prop('class','');
}
else if (selVal == 'Outbound') { // Outbound
$('.Inbound').hide();
$('.Outbound').show();
$("[name$='INopt']").prop('class','')
$("#INsrvOtr").prop('class','')
$("[name$='OUTopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
$('#valIN').val('');
$('div#Inbound').find('span').prop('class','');
}
else {
$('.Inbound').hide();
$('.Outbound').hide();
$('#valOUT').val('');
$('#valIN').val('');
$("[name$='INopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$('div#Inbound').find('span').prop('class','');
$("[name$='OUTopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$('div#Outbound').find('span').prop('class','');
}
});
});
</script>
$(document).ready(function() {
$("input").onchange(function() {
$(this).attr('class','validate[minCheckbox[1],maxCheckbox[1]] checkbox text')
}
});
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>