I am trying to get the checked value in checkbox and display it in some specific format using javascript but somehow I dont know how to do it
I have tried html and javascript and I dont know ajax or jquery so I am trying javascript only
function Hobby()
{
var checkedValue = null;
var inputElements = document.getElementsByClass('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value
document.getElementById("hobbies_value").innerHTML = inputElements;
break;
}
}
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
If checked values are dancing and painting
then output should be
Hobby:#dancing#painting
and I dont want to display it as alert box instead I want to display it on same page
You need to concatenate the values and display them outside the loop. Something like this:
function Hobby()
{
var checkedValue = "";
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue += "#"+inputElements[i].value
}
}
document.getElementById("hobbies_value").innerHTML = checkedValue;
}
Hobby <input class="messageCheckbox" type="checkbox" name="painting" id="painting" value="painting">Painting
<input class="messageCheckbox" type="checkbox" name="dancing" id="dancing" value="dancing">Dancing
<input class="messageCheckbox" type="checkbox" name="sports " id="sports " value="sports ">Sports
<input type="button" value="student_submit" onclick="Hobby()"><br/>
Javascript code is
<div id="hobbies_value"></div>
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 an issue in this javascript code. This code display multiple checked values, but when I unchecked any value it removes all the values from the result. I want to remove only specific unchecked value from the result. Please any one help me.
<script>
window.addEventListener('DOMContentLoaded', function (event) {
var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
area = document.getElementById('text'), i;
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', function (event) {
var e = event.target;
if (e.checked) {
area.value += e.value + '\n',' ';
} else {
area.value ="";
}
}, false);
} }, false);
</script>
HTML
<form action='search1.php' method='GET' id="the_form">
</br>
<tr>
<h2>Select your problem</h2> <b>Do you have difficulty in sleeping?</b>
<input type="checkbox" id='check1' value="Difficulty sleeping">YES/NO<br>
<b>Do you feel dizziness?</b>
<input type="checkbox" id='check1' value="Dizziness ">YES/NO<br>
<b>Do you feel fever?</b>
<input type="checkbox" id='check1' onClick='check()' value='Fever'>YES/NO<br>
<b>Do you have headache?</b>
<input type="checkbox" id='check1' onClick='check()' value='Headache '>YES/NO<br>
<b>Do you feel warm to touch?</b>
<input type="checkbox" id='check1' onClick='check()' value='Warm to touch'>YES/NO<br>
<b>Do you have itching or burning issue?</b>
<input type="checkbox" id='check1' onClick='check()' value='Itching or burning'>YES/NO<br>
<b>Do you have bleeding issue?</b>
<input type="checkbox" id='check1' onClick='check()' value='Bleeding '>YES/NO<br> <br>
<input type='text'id="text" size='100' name='search' ></br></br>
</tr>
<input type='submit' name='submit' value='Search' ></br></br></br>
</form>
The problem is that you're setting area.value = "" whenever you encounter an unchecked box, so this drops all the values from boxes before it. You should initialize the value to the empty string before the loop, and then add only the checked values.
You also have to loop over all the checkboxes in the event handler, not just the checkbox you clicked on, so you can get all the checked values.
window.addEventListener('DOMContentLoaded', function (event) {
var boxes = document.querySelectorAll('#the_form input[type="checkbox"]'),
area = document.getElementById('text'), i;
for (var i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', function (event) {
area.value = "";
for (var j = 0; j < boxes.length; j++) {
if (boxes[j].checked) {
area.value += boxes[j].value + '\n';
}
}
}, false);
}
}, false);
DEMO
So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.
It should display the total when the radio button 'yes' is clicked.
<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
count++;
alert(count);
}
}}
This should do the trick:
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
try this using jquery
Method 1:
alert($('.checkbox_class_here :checked').size());
Method 2:
alert($('input[name=checkbox_name]').attr('checked'));
Method: 3
alert($(":checkbox:checked").length);
Try this code
<br />Apples
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();" />
Javascript
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
alert(count);
}
}
}
FIDDLE DEMO
Thanks to Marlon Bernardes for this.
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
If you have more than one form with different checkbox names in each, the above code will count all checkboxes in all forms.
To get over this, you can modify it to isolate by name.
var le = document.querySelectorAll('input[name="chkboxes[]"]:checked').length;
The initial code was very nearly right. the line
alert(count);
was in the wrong place. It should have come after the second closing brace like this:-
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count);
}
In the wrong place it was giving you an alert message with every checked box.
var checkboxes = document.getElementsByName("fruit");
for(i = 0 ; i<checkboxes.length; i++)
{
if(checkboxes[i].checked==0){checkboxes.splice(i,1);}
}
alert("Number of checked checkboxes: "+checkboxes.length);
function checkboxes(){
var inputs = document.getElementsByTagName("input");
var inputObj;
var selectedCount = 0;
for(var count1 = 0;count1<inputs.length;count1++) {
inputObj = inputs[count1];
var type = inputObj.getAttribute("type");
if (type == 'checkbox' && inputObj.checked) {
selectedCount++;
}
}
alert(selectedCount);
}
<html>
<body>Fruits
<br />
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />Apple
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();"/>
</body>
</html>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Is there a way to uncheck all boxes at once?
I have a 4x4 table of checkboxes and I set all their ID's to "cb". I want to have a button that clears all of them, so I tried doing something like below:
document.getElementById("cb").checked="false"
But on the screen, they still remain checked. Is this possible?
ID's are unique, so having multiple elements with the same ID wont solve the problem, it will only make your markup invalid. Use classes instead:
var boxes = document.getElementsByClassName("cb");
for (i=0; boxes.length<i; i++) {
boxes[i].checked = false;
}
You can use something like this:
function toggle(state) {
var cb = document.getElementsByName('cb');
for (var i = cb.length; i--;) {
cb[i].checked = typeof state != 'undefined' ? state : !cb[i].checked;
}
}
Usage:
toggle(false); // Uncheck all
toggle(true); // Check all
toggle(); // Toggle all
In this example you select checkboxes by the name attribute. You can also use class name and select inputs with document.getElementsByClassName or document.querySelectorAll methods.
Demo: http://jsfiddle.net/kCmqL/1/
Check this article Javascript Check and Uncheck All Checkboxes
Here is the code below:
Script
<script language="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
HTML
<form name="myform" action="checkboxes.asp" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
Best Regards
Try
<script language="javascript">
function checkUnCheckAll(formname)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
</script>
More
You can also your same Name to all controls as below:
<input type="Checkbox" name="compare" id="compare" value="1" />
<input type="Checkbox" name="compare" id="Checkbox1" value="5" />
<input type="Checkbox" name="compare" id="Checkbox2" value="8" />
<input type="Checkbox" name="compare" id="Checkbox3" value="10" />
<input type="button" value="select all" onclick="javascript:checkAll()"/>
<input type="button" value="unckeck all" onclick="javascript: unCheckAll()"/>
<script type="text/javascript">
function checkAll()
{
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = true;
}
}
function unCheckAll() {
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
}
</script>
While you already have an answer, I thought I'd post the following as an option also. Given the following minimal/demonstrative HTML mark-up:
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" checked />
The following JavaScript can be used to check, uncheck or toggle all checkboxes returned by the selector:
Object.prototype.check = function (newState) {
switch (newState.toLowerCase()) {
case 'toggle':
for (var i = 0, len = this.length; i<len; i++){
this[i].checked = !this[i].checked;
}
break;
case 'check':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = true;
}
break;
case 'uncheck':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = false;
}
break;
}
return this;
};
To toggle all, call with (for example):
document.getElementsByClassName('something').check('toggle');.
To check all, call with (for example):
document.getElementsByClassName('something').check('check');.
To uncheck all, call with (for example):
document.getElementsByClassName('something').check('uncheck');.
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
I need a javascript validation to check whether any checkbox is selected or not?
Thanks and Regards
NOTE: I need javascript validation
You can access the DOM elements and check their checked property. For instance:
var list, index, item, checkedCount;
checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a form element), then you can give that element an ID and then look only within it (only the var, form =, and list = lines are new/different):
var form, list, index, item, checkedCount;
checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is much easier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:
var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;
Live example Other libraries will be similar, though the details will vary.
<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
<input type="checkbox" name="midlevelusers[]" value="1" /> 1
<input type="checkbox" name="midlevelusers[]" value="2" /> 2
<input type="checkbox" name="midlevelusers[]" value="3" /> 3
<input type="checkbox" name="midlevelusers[]" value="4" /> 4
<input type="checkbox" name="midlevelusers[]" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type="text/javascript">
function checkTheBox() {
var flag = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["midlevelusers[]"][i].checked){
flag ++;
}
}
if (flag != 1) {
alert ("You must check one and only one checkbox!");
return false;
}
return true;
}
</script>
try,
function validate() {
var chk = document.getElementsByName('midlevelusers[]')
var len = chk.length
for(i=0;i<len;i++)
{
if(chk[i].checked){
return true;
}
}
return false;
}
use id's
<input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">
now you can do
for (var i=1;i<5;i++){
var el = document.getElementById('mlu'+i);
if (el.checked) { /* do something */}
}
This function would alert whether or not a checkbox has any values checked.
function isChecked(checkboxarray){
for (counter = 0; counter < checkboxarray.length; counter++){
if (checkboxarray[counter].checked){
alert("Checkbox has at least one checked");
else{
alert("None checked");
}
You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!
You could use jQuery and do it this way:
if($('input[name="light[]"]:checked').length < 1){
alert("Please enter the light conditions");
}