Get Checkbox total count & save value in textbox if checked - javascript

I have written below code to get a total count of Checked chechbox and save the value checked value comma separated in textbox.
HTML:
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount(this.value);'></label>
<input type="text" name="proId" id="proId">
JS:
function checkCount(elm) {
var cheCount = $(":checkbox:checked").length;
document.getElementById('selectCount').innerHTML = cheCount;
definVal = document.getElementById('proId').value ;
var inval = elm+","+definVal;
document.getElementById('proId').value = inval;
if(cheCount==0){
document.getElementById('proId').value = "";
}
}
Check the output in below image:
My issue is that, when i unchecked the checkbox, its value is adding in textbox instead of getting remove.

Make below changes, just call js method dont send its value
And then check by their classname
function checkCount(elm) {
var checkboxes = document.getElementsByClassName("checkbox-btn");
var selected = [];
for (var i = 0; i < checkboxes.length; ++i) {
if(checkboxes[i].checked){
selected.push(checkboxes[i].value);
}
}
document.getElementById("proId").value = selected.join();
document.getElementById("total").innerHTML = selected.length;
}
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount();'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount();'></label>
<input type="text" name="proId" id="proId">
<div>Total Selected : <span id="total">0</span></div>

Related

How can I select a random amount of checkboxes?

$('#select_all').on('click', function () {
if (this.checked) {
$('.check').each(function () {
this.checked = true;
});
} else {
$('.check').each(function () {
this.checked = false;
});
}
});
$('.check').on('click', function () {
if ($('.check:checked').length == $('.check').length) {
$('#select_all').prop('checked', true);
} else {
$('#select_all').prop('checked', false);
}
});
Need to alter this above Select All code to only select some random amount of check boxes, like below code example. Any help for this?
$(".random-pick").click(function() {
var maxAllowed = 6;
// Count checkboxes
var random_checkboxes = $("#content_subscribtion_ input.checkbox").size();
// Check random checkboxes until "maxAllowed" limit reached
while ($("#content_subscribtion_ input.checkbox:checked").size() < maxAllowed) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * random_checkboxes) + 1;
// Check it
$("#content_subscribtion_ input.checkbox:nth-child(" + random_checkbox + ")").prop("checked", true);
}
return false;
});
Using this tidy little shuffle method, we can create a random array of checkbox indexes, then slice it to a random number. We can then iterate and use jQuery's get() to find the checkbox index in the randomized array to check.
Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
$('#select_all').on('click', function() {
if ($(this).prop('checked')) {
let minnum = 3, maxnum = 6
let rand = Math.min(maxnum, Math.floor(Math.random() * ($('.check').length - 1 - minnum)) + minnum)
//create our keys array
let keyArray = [...Array($('.check').length).keys()].shuffle().slice(0, rand)
keyArray.forEach((chk_i, i) => {
if (i < rand) $($('.check').get(chk_i)).prop('checked', true)
})
} else {
$('.check').prop('checked', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Select all <input type='checkbox' id="select_all"></label>
<div class='cb'>
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
<input type='checkbox' class='check'> checkbox <br />
</div>
I have 8 checkboxes on the UI and I am selecting 3 checkboxes randomly. After each run, different checkboxes will be selected. Please use the exact/clean/proper checkbox common unique identifier in the cy.get('xxxxxx') and use following code in JS:
cy.get('section[class="table-body-cell checkbox-cell grid-1"] input')
.then(
($items) => {
return Cypress._.sampleSize($items.toArray(), 3)
})
.check({force: true});

How to print a new value of a checkbox after having checked it?

I built a form in which I populated checkboxes with values stored in a PostGreSQL database (you can see the snippet). The checkbox are checked or not checked automatically.
Now, if I choose another value of the checkbox, I'd like to display it in an "alert" or "console.log" print.
How could I do in Javascript or Jquery ?
Thanks you very much for the help !
<div class="form-row">
<div id="man-compo" class="form-group col-md-12">
<label for="exampleInputPassword1">Composition (le texte hagiographique est composé de) :</label><br>
<?php
foreach ($checked116 as $value) {
$array12 = array("Textes historiographiques","Actes de la pratique","Textes grammaticaux","Lettres et ars dictaminis","Vers et inscriptions métriques","Lexique","Comput","Algèbre et géométrie","Autres");
$checked = "";
if(in_array($value, $array12)){
$checked = "checked";
echo '<input type="checkbox" id= "checked-man-compo-compo-1" name="checkedmancompocompo1[]" value="'.$value.'" '.$checked.' > '.$value.' <br/>';
}
}
foreach ($array12 as $i) {
$checked = "";
if(in_array($i, $checked116)){
}
else {
echo '<input type="checkbox" id= "notchecked-man-compo-compo-1" name="notcheckedmancompocompo1[]" value="'.$i.'" '.$checked.' > '.$i.' <br/>';
}
}
?>
Here is a simple example of what you're trying to do in plain JavaScript which you can mody/apply to your code.
//get all checkboxes beginning with id 'checkbox'
let checkboxes = document.querySelectorAll( "[ id^=checkbox ]" );
//add event listener to each checkbox, upon being checked/unchecked to print out value
for ( let i = 0; i < checkboxes.length; i++ ) {
checkboxes[ i ].addEventListener( "change", function() {
console.log( checkboxes[ i ].value );
});
}
<label for="checkbox1"> checkbox 1 </label>
<input type="checkbox" id="checkbox1" value=1>
<label for="checkbox2"> checkbox 2 </label>
<input type="checkbox" id="checkbox2" value=2>
<label for="checkbox3"> checkbox 3 </label>
<input type="checkbox" id="checkbox3" value=3>
<label for="checkbox4"> checkbox 4 </label>
<input type="checkbox" id="checkbox4" value=4>
I hope this is of help to you.

How to structure javascript array

I have a dynamic form where you can click a button and a new form row is added to the form. The form entry looks like this:
<input type='text' class='custom' data-index='".$f."' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='".$f."' name='column_value_two' value='2'>
For example, I add 3 lines of the above and data-index is 0 through 3. I try to process it by doing the following:
var data = [];
$(".custom").each(function() {
var index = parseInt($(this).attr('data-index'));
data[index][$(this).attr("name")] = $(this).val();
});
I am trying to have an end result of:
data[0]['column_value_one'] = 1;
data[0]['column_value_two'] = 2;
data[1]['column_value_one'] = 1;
data[1]['column_value_two'] = 2;
I only usually write PHP, hence me laying out the array as per above. But this would be a Javascript/Jquery array not PHP.
I would appreciate any help here.
You need to init the data[index] to {} if the index does not exist.
data[index] = data[index] || {};
Like:
var data = [];
$(".custom").each(function() {
var index = parseInt($(this).attr('data-index'));
data[index] = data[index] || {};
data[index][$(this).attr("name")] = $(this).val();
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='custom' data-index='0' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='2'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='2'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='1'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='2'>
It sounds like you want an array of objects:
data = [
{column_value_one: 1, column_value_two: 2},
// ...
];
In that case, since the second input follows the first, you could do:
var data = $("input[name=column_value_one]").map(function() {
return {column_value_one: this.value, column_value_two: $(this).next().val()};
}).get();
Live Example:
var data = $("input[name=column_value_one]").map(function() {
return {column_value_one: this.value, column_value_two: $(this).next().val()};
}).get();
console.log(data);
<input type='text' class='custom' data-index='0' name='column_value_one' value='11'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='12'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='21'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='22'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='31'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='32'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Or if you may have something in-between them, use two jQuery objects:
var ones = $("input[name=column_value_one]");
var twos = $("input[name=column_value_two]");
var data = ones.map(function(index) {
return {column_value_one: this.value, column_value_two: twos.eq(index).val()};
}).get();
var ones = $("input[name=column_value_one]");
var twos = $("input[name=column_value_two]");
var data = ones.map(function(index) {
return {column_value_one: this.value, column_value_two: twos.eq(index).val()};
}).get();
console.log(data);
<input type='text' class='custom' data-index='0' name='column_value_one' value='11'>
<input type='text' class='custom' data-index='0' name='column_value_two' value='12'>
<input type='text' class='custom' data-index='1' name='column_value_one' value='21'>
<input type='text' class='custom' data-index='1' name='column_value_two' value='22'>
<input type='text' class='custom' data-index='2' name='column_value_one' value='31'>
<input type='text' class='custom' data-index='2' name='column_value_two' value='32'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In both cases, there's no need for data-index (for this; maybe you need it for something else).

Jquery change hidden input value in for loop

I try to change each hidden input value if checkbox is checked using jquery
I need to using for loop because html input field is generate by php loop from db too. so here is generated html code look like :
Html :
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="" type="hidden">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="" type="hidden">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="" type="hidden">
Jquery :
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = '#gift' + i;
var val = '#gift-true' + i;
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
but this code didn't work.
P.S :
code to generate html input is look like this :
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' id='gift$i' name='exm$i' value='1'> <br>
<input type='hidden' id='gift-true$i' value=''></td> <br><br>";
}
You can do this by using next() function as all the inputs are next to the checkbox. please replace var tot = 3; with var tot = <?php echo $tot; ?>; and type="text" with type="hidden"
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Changes this two value in your code
var chk = $('#gift' + i).val();
var val = $('#gift-true' + i).val();
This is what u want i guess
var tot = 3;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
$(this).next().val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">
<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">
<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">
Try this
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = $('#gift' + i);
var val = $('#gift-true' + i);
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});
You need to get object instead of string right now you are getting a string which is '#gift' + i. Wrap it inside $('#gift' + i) to get the object.
Only relevant input should be set on change of a checkbox. You should not loop again for each input on change event.
var tot = <?php echo $tot; ?>;
jQuery(function($){
for (var i = 0; i< tot; i++ ){
$('#gift' + i).on('change', function(e) {
// no need for another loop as you should target only relevant input field
$('input#gift-true' + i).val(($(this).is(':checked')) ? "yes" : "no");
});
}
});
Yo do not need loop here. Just change the value of the next input.
$('input[type="checkbox"]').change(function(){
var $hidden = $(this).next('input[type="hidden"]');
if ($hidden.length) {
var checked = $(this).is(':checked');
if (checked) {
$hidden.val('yes');
} else {
$hidden.val('no');
}
}
});
//call function for every checkbox which are already on page
$('input[type="checkbox"]').change();
This code will work for every checkbox on the page. To avoid this just use stronger selector: $('.some-class input[type="checkbox"]')
My answer, similar to a few others, also eliminates the for loop.
jQuery(function ($) {
// do this if you do not know the state of the generated checkbox
$("input[type='checkbox']").each(function () {
$(this).next().val($(this).prop("checked") ? "yes" : "no");
});
// then this for your event handler
$("input[type='checkbox']").on("change", function (e) {
$(e.target).next().val($(e.target).prop("checked")?"yes":"no");
})
});
Change you id to class
<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' class='gift' name='exm$i' value='1'> <br>
<input type='hidden' name='gift-exm$i' class='gift-true' value=''></td> <br><br>";
}
refactor your code as follows
$('.gift').change(function(e) {//remove any loops /keep the change event
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");//select the hidden input using next()
});
ps: don't forget to add a name to the hidden input
$('.gift').change(function(e) {
var el = $(this);
el.next('.gift-true').val(el.is(':checked') ? "yes" : "no");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">
<input class="gift" value="1" type="checkbox">
<input class="gift-true" value="no" type="text">

Jquery change checkbox when clicking other checkbox

I have a list of checkboxes like this:
<input type='checkbox' name='cat' class='parent' value='cat1' />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='1' />SubCategory 2</input>
<input type='checkbox' name='cat' class='parent' value='cat2' />Category 2</input>
<input type='checkbox' name='foo' class='child' value='3' />SubCategory 3</input>
<input type='checkbox' name='foo' class='child' value='4' />SubCategory 4</input>
I would like to change the 'Category 1' checkbox to checked whenever I click it's subcategories without checking the other categories checkbox.
How can I do that?
Using the data attribute to set the cat. simply get this form the check event of the child elements:
<input type='checkbox' name='cat' class='parent' value='cat1' id="category1" />Category 1</input>
<input type='checkbox' name='foo' class='child' value='1' data-cat="1" />SubCategory 1</input>
<input type='checkbox' name='foo' class='child' value='2' data-cat="1" />SubCategory 2</input>
....
$('.child').change(function() {
var cat = $(this).data('cat');
$('#category' + cat).prop('checked', true);
});
I made a slight change to your markup and wrapped the sets in a div each.
Now my code will uncheck the parent too if all its child-cats are unchecked and when you check the parent, all child cats are checked/unchecked
Live Demo
$(function() {
$(".child").on("click",function() {
$parent = $(this).prevAll(".parent");
if ($(this).is(":checked")) $parent.prop("checked",true);
else {
var len = $(this).parent().find(".child:checked").length;
$parent.prop("checked",len>0);
}
});
$(".parent").on("click",function() {
$(this).parent().find(".child").prop("checked",this.checked);
});
});
You can id the subCategories as cat2_1, cat2_2 etc and then access the category element by means of the subcategory element by splitting the id by _ to obtain the category id.
Other answer
$(document).ready(function () {
$("INPUT").click(function () {
if ($(this).attr("class") == "parent") {
var v = this.value;
var check = this.checked;
var ok = false;
$("INPUT").each(function () {
if (v == this.value) {
ok = true;
} else {
if (this.name=="cat") ok = false;
else if (ok && this.name == "foo") {
this.checked=check;
}
}
});
}
});
});

Categories