$('#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});
Related
I have a list of checkboxes, and I need to disable my submit button if none of them are checked, and enable it as soon as at least one gets checked. I see lots of advice for doing this with just a single checkbox, but I'm hung up on getting it to work with multiple checkboxes. I want to use javascript for this project, even though I know there are a bunch of answers for jquery. Here's what I've got - it works for the first checkbox, but not the second.
HTML:
<input type="checkbox" id="checkme"/> Option1<br>
<input type="checkbox" id="checkme"/> Option2<br>
<input type="checkbox" id="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
I'd group your inputs in a container and watch that for events using addEventListener. Then loop through the checkboxes, checking their status. Finally set the button to disabled unless our criteria is met.
var checks = document.getElementsByName('checkme');
var checkBoxList = document.getElementById('checkBoxList');
var sendbtn = document.getElementById('sendNewSms');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
<div id="checkBoxList">
<input type="checkbox" name="checkme"/> Option1<br>
<input type="checkbox" name="checkme"/> Option2<br>
<input type="checkbox" name="checkme"/> Option3<br>
</div>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
html
<input type="checkbox" class="checkme"/> Option1<br>
<input type="checkbox" class="checkme"/> Option2<br>
<input type="checkbox" class="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
js
var checkerArr = document.getElementsByClassName('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
for (var i = 0; i < checkerArr.length; i++) {
checkerArr[i].onchange = function() {
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
}
I guess this code will help you
window.onload=function(){
var checkboxes = document.getElementsByClassName('checkbox')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkbox"/> Option1<br>
<input type="checkbox" id="check2" class="checkbox"/> Option2<br>
<input type="checkbox" id="check3" class="checkbox"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Few suggestions
1.Always id should be unique. HTML does not show any error, if you give multiple objects with the same id but when you try to get it by document.getelementbyid it always return the first one,because getelementbyid returns a single element
when there is such requirement, you should consider having a classname or searching through the element name because getelementsbyclassname/tag returns an array
Here in the markup i have added an extra class to query using getelementsbyclassname
To avoid adding extra class, you can also consider doing it by document.querySelectorAll
check the following snippet
window.onload=function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" /> Option1<br>
<input type="checkbox" id="check2" /> Option2<br>
<input type="checkbox" id="check3" /> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Hope this helps
Something like this would do. I'm sure you can do it with less code, but I am still a JavaScript beginner. :)
HTML
<input type="checkbox" class="checkme" data-id="checkMe1"/> Option1<br>
<input type="checkbox" class="checkme" data-id="checkMe2"/> Option2<br>
<input type="checkbox" class="checkme" data-id="checkMe3"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
JavaScript
//keep the checkbox states, to reduce access to the DOM
var buttonStatus = {
checkMe1: false,
checkMe2: false,
checkMe1: false
};
//get the handles to the elements
var sendbtn = document.getElementById('sendNewSms');
var checkBoxes = document.querySelectorAll('.checkme');
//add event listeners
for(var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('change', function() {
buttonStatus[this.getAttribute('data-id')] = this.checked;
updateSendButton();
});
}
//check if the button needs to be enabled or disabled,
//depending on the state of other checkboxes
function updateSendButton() {
//check through all the keys in the buttonStatus object
for (var key in buttonStatus) {
if (buttonStatus.hasOwnProperty(key)) {
if (buttonStatus[key] === true) {
//if at least one of the checkboxes are checked
//enable the sendbtn
sendbtn.disabled = false;
return;
}
}
}
//disable the sendbtn otherwise
sendbtn.disabled = true;
}
var check_opt = document.getElementsByClassName('checkit');
console.log(check_opt);
var btn = document.getElementById('sendNewSms');
function detect() {
btn.disabled = true;
for (var index = 0; index < check_opt.length; ++index) {
console.log(index);
if (check_opt[index].checked == true) {
console.log(btn);
btn.disabled = false;
}
}
}
window.onload = function() {
for (var i = 0; i < check_opt.length; i++) {
check_opt[i].addEventListener('click', detect)
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkit" />Option1
<br>
<input type="checkbox" id="check2" class="checkit" />Option2
<br>
<input type="checkbox" id="check3" class="checkit" />Option3
<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="true" id="sendNewSms" value=" Send " />
I have Jquery/Javascript function which calculates certain field values. One of the field returns a value in
function calcTotals() {
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
}
I have another function with a checkbox
function recalcTotal() {
var total12 = 0;
$('input:checked').each(function () {
total12 += $(this).marginObj.value;
});
$('#total12').val(total12);
}
$("input[type='checkbox']").on("click", function () {
recalcTotal();
});
I need to pass the values from the marginObj.value to the next function that is total12 += $(this).marginObj.value; What iam trying to achieve is iam taking the values from marginObj.value and there is a checkbox, if i check the checbox it totals all the checked values and show it in grandTotal field.
<input name="grandTotal" id="total12" readonly/>
Please check the complete script.
FIDDLE
So what i want is there are some values in Margin with a checkbox. When i check any checkbox, its should total the selected checkboxes and show in the Grand Total field.
I am guessing the issue is getting the marginObj which is an input element after check box.
$(function () {
recalcTotal();
$("input[type='checkbox'").on("click", function () {
recalcTotal();
});
function recalcTotal() {
var total = 0.0;
$("input:checked").each(function () {
total += $(this).next("input").val() * 1.0;
});
$("#total").val(total.toFixed(3));
}
});
<input type="text" id="total" readonly/> <br />
<input type="checkbox" name="values"/><input type="text" readonly value="1"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="2"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="3"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="4"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="5"/> <br />
<input type="checkbox" name="values" /><input type="text" readonly value="6"/> <br />
Not 100% what you are asking, but if you are simply trying to pass a value from one function to another, there are multiple approaches, but the simplest is to pass arguments to the function.
//this function supports 1 argument
function calcTotals( amount ) {
//add 1 and return
return amount + 1;
}
//calling this argument
var amount = 5;
var newAmount = calcTotals( amount );
assuing marginObj is globally accessible.
function recalcTotal() {
var total12 = 0;
$('input:checked').each(function () {
total12 += $(this).marginObj.value;
});
$('#total12').val(total12);
}
$("input[type='checkbox']").on("click", function () {
calcTotals(); -- will populate marginObj.value
recalcTotal();
});
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;
}
}
});
}
});
});
I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});
I want to have the first checkbox that allows me to check or uncheck all of the other boxes. Here is the code I am using:
<html>
<head>
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsById('checkall');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
</head>
<body>
<input type='checkbox' onClick='toggle(this)' /><br />
<input type='checkbox' id='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' id='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' id='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
This has worked for me.
function toggle(oInput) {
var aInputs = document.getElementsByTagName('input');
for (var i=0;i<aInputs.length;i++) {
if (aInputs[i] != oInput) {
aInputs[i].checked = oInput.checked;
}
}
}
Though, if you want to limit this to only certain checkboxes, add a classname to them, and to the master checkbox
<html>
<head>
<script type="text/javascript">
function toggle(source) {
var aInputs = document.getElementsByTagName('input');
for (var i=0;i<aInputs.length;i++) {
if (aInputs[i] != source && aInputs[i].className == source.className) {
aInputs[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<input type='checkbox' class='checkall' onClick='toggle(this)' /><br />
<input type='checkbox' class='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' class='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' class='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' class='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' class='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
The problem is you are using the same id for all the checkbox groups. An id must be unique to a page. Instead you may use the checkbox name. Since the names have [] with varying values, you can use indexOf to examine just the first part.
<html>
<head>
<script language="JavaScript">
function toggle(source) {
// Get all input elements
var inputs = document.getElementsByTagName('input');
// Loop over inputs to find the checkboxes whose name starts with `orders`
for(var i =0; i<inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].name.indexOf('orders') === 0) {
inputs[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<input type='checkbox' onClick='toggle(this)' /><br />
<input type='checkbox' id='checkall' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' id='checkall' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' id='checkall' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' id='checkall' name='orders[4][order_id]' value='17011' /><br />
</body>
</html>
Try this...
<form id="form_">
<input type='checkbox' name='item1' value='16885' />
<input type='checkbox' name='item1' value='17006' />
<input type='checkbox' name='item1' value='17006' />
<input type='checkbox' name='item1' value='17007' />
<input type='checkbox' name='item1' value='17011' />
<br/>Select All
<br/>Clear All
<button id="btnRemove1"><br/>Remove</button>
</form>
<script>
$("#select_all1").click(function() {
var item = document.getElementsByName("item1");
for (var i=0; i < item.length; i++) {
item[i].setAttribute("checked");
}
});
$("#clear_all1").click(function() {
var item = document.getElementsByName("item1");
for (var i=0; i < item.length; i++) {
if(item[i].checked) {
item[i].removeAttribute("checked");
} else {
alert("Nothing to clear.");
return false;
}
}
});
$("#btnRemove1").click(function() {
var items = $('.item1').is(':checked');
if(items) {
window.location = "/contents?"+ $("form#form_").serialize();
}
else {
alert("Nothing to remove.");
return false;
}
});
</script>
It's better to use the querySelectorAll. here is the example.
The Html with checkboxes
<input type="button" value="Select All" onclick="selectAll()" id="TestAll" />
<input type='checkbox' id='checkAll' name='Test1' />
<input type='checkbox' id='checkall' name='Test2' />
<input type='checkbox' id='checkAll' name='Test3' />
<input type='checkbox' id='checkAll' name='Test4' />
<input type='checkbox' id='checkAll' name='Test5' />
Here is the javascript for this
function selectAll() {
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox')
checkboxes[i].checked = true;
}
}
IDs are supposed to be unique - never have more than one HTML element with the same id, it's invalid. That's also why you have a problem - there is no such method as document.getElementsById, only document.getElementById. Instead, you could use classes. Here's how to solve your problem in pure JavaScript:
function toggle(source) {
var inputs = document.getElementsByTagName('input');
var i, input;
for(i = 0; input = inputs[i]; i++) {
if((' ' + input.className + ' ').indexOf(' checkall ') > -1) {
input.checked = source.checked;
}
}
}
And change all your id="checkall"s to class="checkall".
Or you could use jQuery. It's great and does all things ;)
You can simply wrap all checkboxes that you nead itterate throu into the DIV and access to it's childNodes and use getElementById to access that DIV
<head>
<script language="JavaScript">
function toggle(source) {
//use getElementById to access to DOM objects by ID
var checkboxes = document.getElementById('checkall').childNodes;
var source = document.getElementById('source');
//now just itterate throu all checkboxess that is in the 'checkall' DIV
for(var i in checkboxes) {
checkboxes[i].checked = source.checked;
}
}
</script>
</head>
<body>
<!--Give an ID to the source checkbox so we could access it from Javascript-->
<input id="source" type='checkbox' onClick='toggle(this)' /><br />
<!--Just wrap all checkboxes that you nead to itterate into the DIV-->
<div id="checkall">
<input type='checkbox' name='orders[0][order_id]' value='16885' /><br />
<input type='checkbox' name='orders[1][order_id]' value='17006' /><br />
<input type='checkbox' name='orders[2][order_id]' value='17006' /><br />
<input type='checkbox' name='orders[3][order_id]' value='17007' /><br />
<input type='checkbox' name='orders[4][order_id]' value='17011' /><br />
</div>
</body>
</html>