Javascript - Returning values from checkboxes - javascript

I have some checkboxes which feature days of the week. I simply want to loop through, and display all those selected within an append.
HTML
<div class="col-lg-8">
<input type="checkbox" value="Mon" class="dayname" name="days[]"> M
<input type="checkbox" value="Tues" class="dayname" name="days[]"> T
<input type="checkbox" value="Wed" class="dayname" name="days[]">W
<input type="checkbox" value="Thurs" class="dayname" name="days[]">T
<input type="checkbox" value="Fri" class="dayname" name="days[]">F
<input type="checkbox" value="Sat" class="dayname" name="days[]">S
<input type="checkbox" value="Sun" class="dayname" name="days[]">S
</div>
Javascript
$(".dayname").click(function() {
alert( $(this).attr("name") );
$('.dayname').val();
});

Try this: JSFIDDLE
$(".dayname").click(function() {
alert( $(this).attr("name") );
$('#log').html(''); // Clears the log div
$('.dayname:checked').each(function(e){
$('#log').append('<p>'+$(this).val()+'</p>');
});
});

Use .map().get():
$(".dayname").change(function() {
var days = $('.dayname:checked').map(function(){
return this.value;
}).get();
console.log(days); // prints the checked checkboxes values
});

var checkedDays=[];
$(".dayname").click(function() {
//alert( $(this).attr("name") );
$('.dayname:checked').each(function(e){
//alert($(this).val());
});
checkedDays.push($(this).val());
alert(checkedDays);
});

$(".dayname").click(function() {
alert( $(this).attr("value") );
});
Or
$(".dayname").change(function() {
if($(this).is(":checked")) {
alert($(this).attr('value'));
}
});

Related

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>

jquery add / remove item from array

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>

Label -> Checkbox Text

I have this problem..
I have this HTML code for 2 groups of checkbox:
<label class="checkbox"><input type="checkbox" onClick="toggle_colors(this)" checked><i></i>All Colors</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox"><input type="checkbox" onClick="toggle_brands(this)" checked><i></i>Tutte le Marche</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Asus</label>
And I use this javascripts for select all/toggle all:
function toggle_brands(source) {
checkboxes = document.getElementsByName('brand');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function toggle_colors(source) {
checkboxes = document.getElementsByName('colore');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
When the user click on the checkbox I need to know if the checkbox is selected or not, to send the details of the query by AJAX..
To know if the checkbox I use this javascript:
$( "[type=checkbox]" ).change(function() {
if(this.checked) {
alert('checked');
}
else {
alert('unchecked');
}
});
I want the text at the right of the selected checkbox..!
Ok.. With the parent work fine!
I have added this code to create the query:
function create_query(){
var query = "SELECT * FROM computers ORDER BY " + ($("#ordine option:selected").val()) + " LIMIT " + ($("#risultati option:selected").val());
$.ajax({
type: "POST",
url: "static/cerca_prodotti.php",
data: "query="+query,
dataType: "html",
success: function(risposta){
$("div#risultati").html(risposta);
},
})
}
$( "[type=checkbox]" ).change(function() {
if(this.checked) {}
else {}
});
$("#ordine").change(function() {
create_query();
});
But I need to modify the query when the checkbox was checked/unchecked!
When you change the checked property programatically, the change event will not get triggered, you need to trigger the event manually.
$('input[data-all-type]').change(function() {
$('input[name="' + $(this).data('allType') + '"]')[this.checked ? 'not' : 'filter'](':checked').prop('checked', this.checked).change();
})
$("input[type=checkbox]:not([data-all-type])").change(function() {
if (this.checked) {
console.log('checked', this);
} else {
console.log('unchecked', this);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" name="color-all" data-all-type="colore"><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" name="brand-all" data-all-type="brand"><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Asus</label>
You can do that with only one function
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', $(source).is(':checked'))
//OR
$('input[name="' + things + '"]').prop('checked', source.checked);
}
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', source.checked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'colore')" checked><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'brand')" checked><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Asus</label>
You can get text of the parent node of the checkbox in this way:
$( "[type=checkbox]" ).change(function() {
var text = this.parentElement.innerText;
if(this.checked) {
alert(text + ': checked');
}
else {
alert(text + ': unchecked');
}
});

Alert when selected similar value from multiple check box with the same class name

When I select for a second time from the below check box with the same value it should alert 'value is already checked' How do I do that using jquery?
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="2"/>
</div>
<div>
<input type="checkbox" class="check" value="1"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
<div>
<input type="checkbox" class="check" value="4"/>
</div>
<div>
<input type="checkbox" class="check" value="3"/>
</div>
I tried with below code but nothing is working
var itemVal=false;
$(document).on('change','.check:checked',function(){
selVal=$(this).val();
$('.check:checked').each(function(){
if($(this).val()==selVal)
itemVal=true;
});
if(itemVal==true){
alert('Proceed');
}else{
alert('Please choose same name');
}
});
Try this:
$('.check').change(function(event){
var arr = $(".check:checked").map(function() {
return $(this).val();
}).get();
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
if(results.length >0){
alert('value is already checked')
}
});
Demo:
http://jsfiddle.net/9a8o37h0/1/
Like this:
$('.check').click(function () {
if(!this.checked)
alert("Value is already Checked");
});
If you want to keep it checked add this before the alert
this.checked = true;

Checking all checkboxes at once with Javascript

This function alerts right totalqt only when I check checkboxes one by one. But doesn't work properly for #check_all: alerts totalqt = 0.
What I did wrong, can anyone explain?
var totalqt=0;
$('#check_all').click( function() {
$('.checkbox').click();
alert(totalqt);
} );
$('.checkbox').click(function(e) {
e.stopPropagation();
if($(this).closest("tr").not('#hdr').hasClass("row_selected")){
$(this).closest("tr").not('#hdr').removeClass("row_selected");
totalqt=totalqt - parseInt($(this).closest("tr").find("#qt").text(), 10);
}
else {
$(this).closest("tr").not('#hdr').addClass("row_selected");
totalqt=totalqt + parseInt($(this).closest("tr").find("#qt").text());
}
HTML looks like that
<tr>
...
<td><input type="checkbox" name="checkbox[]" method="post" value="" class="checkbox"/></td>
...
</tr>
actually when the checkbox is changed manualy it doesn't trigger handler. try something like this.
function doIt(obj){
if($(obj).closest("tr").not('#hdr').hasClass("row_selected")){
$(obj).closest("tr").not('#hdr').removeClass("row_selected");
totalqt=totalqt - parseInt($(obj).closest("tr").find("#qt").text(), 10);
}
else {
$(obj).closest("tr").not('#hdr').addClass("row_selected");
totalqt=totalqt + parseInt($(obj).closest("tr").find("#qt").text());
}
}
then
$('.checkbox').click(function(e) {
e.stopPropagation();
doIt(this);
});
and
$('#check_all').click( function() {
if($(this).prop('checked')){
$('.checkbox').each(function(){
$(this).prop('checked', true);
doIt(this);
alert(totalqt);
});
}else{
$('.checkbox').each(function(){
$(this).prop('checked', false);
doIt(this);
alert(totalqt);
});
}
} );
I have changed my answer to the following, try this:
<div class="checkall">
<input type="checkbox" id="checkall">
</div>
<div id="list">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
and jquery:
var checkboxes = $(":checkbox", "#list").change(function() {
var allIsChecked = checkboxes.length === checkboxes.filter(":checked").length;
checkAll[0].checked = allIsChecked;
});
var checkAll = $("#checkall").change(function() {
checkboxes.prop("checked",this.checked);
});

Categories

Resources