I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
Related
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.
This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>
You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.
When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>
Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>
I have created multiple checkboxes using a script in an HTML file.
I want to updates the checkboxes using name based on a condition like the below.
Checkboxes[I].checked = true;
But it's throwing an error.
Can you please suggest a way to solve this issue out.
for this purpose I will try to answer you, I have two options, by class or tag name, may if you want to use Jquery its also nice. I prepare an example for you, I hope that this one helps you, greetings
function toggleA() {
var elm = document.getElementsByClassName('chx');
for(var i = 0; i < elm.length; i++) {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
function toggleB() {
var elm = $(".chx").prop("checked")
$(".chx").prop( "checked", !elm );
}
function toggleC() {
var elm = document.getElementsByTagName('input');
for(var i = 0; i < elm.length; i++) {
if(elm[i].type.toLowerCase() == 'checkbox') {
elm[i].checked = !elm[i].checked;
// alert(elm[i].value);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" onclick="toggleA()">Toggle A</button>
<button id="btn" onclick="toggleB()">Toggle B</button>
<button id="btn" onclick="toggleC()">Toggle C</button>
<br><br>
<label>
<input id="check-a" class = "chx" onchange="alert('Changed A!')" type="checkbox"> A
</label>
<br><br>
<label>
<input id="check-b" class = "chx" onchange="alert('Changed B!')" type="checkbox"> B
</label>
<br><br>
<label>
<input id="check-jq" class = "chx" onchange="alert('Changed JQ!')" type="checkbox"> JQ
</label>
<br><br>
<label>
<input id="check-c" class = "chx" onchange="alert('Changed C!')" type="checkbox"> C
</label>
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'm trying to get the number of checkBoxes checked with using the information from an array but I keep getting undefined. I have to use an array, a switch, and must be in JavaScript for this project. I can't use any other programming Language.
How can I get my function to correctly add the checked boxes?
I am also not sure on how I could implement a switch into this function.+
Please help, I've been working on this for about 4 hours, searching everywhere to find a helpful answer.
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project</title>
</head>
<body>
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<th>Directions: Check of the items you think you would enjoy in each section.<br /> Mark as many items that apply.</th>
<tr><td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic1">Repair a car
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic2">Do wood working
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox"
name="chkRealistic"
onclick="getRealistic()"
value="chkRealistic4">Explore a forest
<br />
</tr></td>
</table><!--End of tblWhichCareer-->
</form><!--End of frmWhichCareer-->
</body>
</html>
My JavaScript
Global Variables
var getCareer = new Array();
getCareer["chkRealistic1"] = 1;
getCareer["chkRealistic2"] = 1;
getCareer["chkRealistic3"] = 1;
getCareer["chkRealistic4"] = 1;
function getRealistic()
{
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
rTotal = getCareer[selectedRealistic.value]
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}//End of function getRealisticCareer()
You missed the fact that this line
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
returns an array of checkboxes with the name chkRealistic (in your example, all four of them).
Instead of assigning the result of the getCareer function to rTotal, you should iterate through the array of HTMLInput in selectedRealistic checking for the .checked property.
var rTotal = 0;
var selectedRealistic = document.forms["frmCareer"]["chkRealistic"];
for (var sel = 0; sel < selectedRealistic.length; sel++)
{
if (selectedRealistic[sel].checked)
rTotal += getCareer[selectedRealistic[sel].value]
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
You can check a running example here: http://codepen.io/pabloapa/pen/jPNPNg
Try using:
document.getElementById("lblRealistic").innerHTML = document.querySelectorAll('input[name="chkRealistic"]:checked').length + "/9 Checked";
Try this:
function getRealistic()
{
var rTotal = 0;
for(i=0; i<document.forms[0].chkRealistic.length; i++){
if(document.forms[0].chkRealistic.item(i).checked){
rTotal++;
}
}
document.getElementById("lblRealistic").innerHTML = rTotal+ "/9 Checked"
}
Here try this also on Plunker: http://plnkr.co/edit/085ZtojBgvumktHwQSGf?p=preview
<form id="frmCareer" method="get" action="prjFormEvent.js">
<table id="tblCareer">
<tr>
<th>Directions: Check of the items you think you would enjoy in each section.
<br />Mark as many items that apply.</th>
</tr>
<tr>
<td><strong><label id="lblRealistic">
"R" Section</label></strong>
<div id="realisticTotal"></div>
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic1">Repair a car
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic2">Do wood working
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic3">Refinish furniture
<br />
<input type="checkbox" name="chkRealistic" onchange="getRealistic(this)" value="chkRealistic4">Explore a forest
<br />
</td>
</tr>
</table>
<!--End of tblWhichCareer-->
</form>
<!--End of frmWhichCareer-->
<script language="JavaScript">
var getCareer = new Array();
getCareer["chkRealistic1"] = 0;
getCareer["chkRealistic2"] = 0;
getCareer["chkRealistic3"] = 0;
getCareer["chkRealistic4"] = 0;
function getRealistic(cbox) {
var rTotal = 0;
var key = cbox.value;
getCareer[key] = cbox.checked ? 1 : 0;
for (var key in getCareer) {
rTotal += getCareer[key];
}
document.getElementById("lblRealistic").innerHTML = rTotal + "/9 Checked"
} //End of function getRealisticCareer()
</script>
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);
}
});