CheckBox Validation in javascript failing for single checkbox - javascript

I have checkboxes created dynamically on the JSP page as follows
<form name="CancelForm" onsubmit="return validate();" action="ServletCancel" method="post">
<%
for(int index=0 ; index<lstID.size() ; index++)
{
String strBookingID = lstID.get(index);
%>
<input type="checkbox" name="BookingID" value="<%=strBookingID%>">
<%
}%>
<input type="submit" value="Cancel" class="button1"/>
</form>
For validating same I have the below JavaScript code to validate that atleast one Checkbox in the Form is checked, if so it should return "true" else "false" with an alert to check atleast one option.
function validate() {
var flag = "false";
var CHKBBookingID = document.CancelForm.BookingID;
alert("length of checkboxes >> "+CHKBBookingID.length)
for (var i = 0; i < CHKBBookingID.length ; i++) {
if (CHKBBookingID[i].checked == true) {
flag = "true";
}
}
if(flag == "false"){
alert("You have not selected any passenger yet!");
return false;
} else {
return true;
}
}
This validation is working Perfectly fine if I have 2 or more Checkboxes in the form.
But on the other hand if I have only one Checkbox the validation alert shows the "Length" of Checkbox as "undefined" as well as fails even though the only Checkbox on the form is checked

var CHKBBookingID = document.CancelForm.BookingID;
Causes the problem. if you are naming it as var it is considered as the variable , as you pass a single element.
so you need to initialize the javascript array as ,
var CHKBBookingID = Array(document.CancelForm.BookingID)
will input them into the array
Learn More. .
Update:
Using jquery you can easily get the number of checkboxes,
var CHKBBookingID = new Array();
$.each($("input[name='BookingID[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});

Related

how to disable a check box using java script conditionally

i have 3 check boxes in 3 different pages,i want to check one check box at time means at first all 3 are unchecked and if i checked one check box remaining 2 check boxes should be disable.
each check box value i am storing in 3 different text file using array in the form of 1's and 0's.
now for one page i am reading check box values and based condition trying to disable check box but its not working.
I have Tried this
check box html code:
input type="checkbox" id="cb1" name="check[0]" value="1" />
java script:
<script type="text/javascript">
var cb1 =document.getElementById("cb1");
var cb2 = "<?php echo $cb2_arr[5] ?>" ; //cb2=1 or 0
var cb3 = "<?php echo $cb3_arr[6] ?>"; //cb3=1 or 0
if(cb2 ==1 || cb3 == 1){
cb1.disabled = true;
}else{
cb1.disabled = false;
}
</script>
cb1.disabled = true; for me its not working i kept alert statements above and below it ,only above one is displayed
Please help me how to set disabled property, thanks
try this to disabled and remove disabled,
if ($('#cb3').is(':checked') || $('#cb2').is(':checked')) {
$('#cb1').setAttribute('disabled', true);
}else{
$('#cb1').setAttribute('disabled', false);
}
You need to check input1.value == "", not simply input1 == ""
You also need to fire your method originally, and also run it every time your select lists change value.
Give the function a name
function setCheckState(evt) {
if (input1.value == "" || input2.value == "") {
result.disabled = true;
} else {
result.disabled = false;
}
}
Add event listeners
input1.addEventListener('change', setCheckState);
input2.addEventListener('change', setCheckState);
// Fire the method to get the initial checkbox state set
setCheckState();
Finally, you can reduce your if() statement to a simple assignment...
function setCheckState(evt) {
result.disabled = input1.value == "" || input2.value == "";
}

function not working in jsp page?

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

When "check-all" box checked, check others

I have a form located on my html page with a bunch of checkboxes as options. One of the options is "check-all" and I want all the other check boxes to be checked, if unchecked, as soon as the "check-all" box is checked. My code looks something like this:
<form method = "post" class = "notification-options">
<input type = "checkbox" name = "notification-option" id = "all-post" onClick = "javascript:checkALL(this
);"> All Posts <br/>
<input type = "checkbox" name = "notification-option" id = "others-post"> Other's Posts <br/>
<input type = "checkbox" name = "notification-option" id = "client-post"> Cilent's Post <br/>
<input type = "checkbox" name = "notification-option" id = "assign-post"> Task Assigned </form>
java script:
<script type = "text/javascript">
var $check-all = document.getElementbyId("all-post");
function checkALL($check-all){
if ($check-all.checked == true){
document.getElementByName("notification-option").checked = true;
}
}
</script>
nothing happens when I run my code
Here are some guidelines.
type attribute is not needed and can be omitted.
JS variable names can't contain hyphens, a typo in
getElementById()
You're using a global variable name as an argument, in the same time
you're passing this from online handler. The passed argument shadows the
global within the function.
if (checkAll.checked) does the job
Typo in getElementsByName(), gEBN() returns an HTMLCollection,
which is an array-like object. You've to iterate through the
collection, and set checked to every element separately.
Fixed code:
<script>
var checkAll = document.getElementById("all-post");
function checkALL(){
var n, checkboxes;
if (checkAll.checked){
checkboxes = document.getElementsByName("notification-option");
for (n = 0; n < checkboxes.length; n++) {
checkboxes[n].checked = true;
}
}
}
</script>
You can also omit the javascript: pseudo-protocol and the argument from online handler.
You can do it like this using jQuery:
$("#all-post").change(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
Here is a JSfiddle
if all post check box is checked it will set check=true of others-post and client-post check boxes
$("input[id$=all-post]").click(function (e) {
if ($("input[id$=all-post]").is(':checked')) {
$("input[id$=others-post]").prop('checked', true);
$("input[id$=client-post]").prop('checked', true);
}
});
Check to see if any of the checkboxes are not checked first.
If so, then loop through them and check any that aren't.
Else, loop through them and uncheck any that are checked
I have an example at http://jsbin.com/witotibe/1/edit?html,output
http://jsfiddle.net/AX3Uj/
<form method="post" id="notification-options">
<input type="checkbox" name="notification-option" id="all-post"> All Posts<br>
<input type="checkbox" name="notification-option" id="others-post"> Other's Posts<br>
<input type="checkbox" name="notification-option" id="client-post"> Cilent's Post<br>
<input type="checkbox" name="notification-option" id="assign-post"> Task Assigned
</form>
function checkAll(ev) {
checkboxes = document.getElementById('notification-options').querySelectorAll("input[type='checkbox']");
if (ev.target.checked === true) {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = true;
}
} else {
for (var i = 0; i < checkboxes.length; ++i) {
checkboxes[i].checked = false;
}
}
}

Checkbox validator

I have a list of checkboxes and I would want to make sure that the user will check at least one before submitting the form. How can I do this?
There are 3 categories then 10 items under each category with a checkbox.
I'm thinking of doing this in javascript wherein I will have a hidden variable then when the user will check any of the checkboxes, the hidden variable will have 1 as its value then if the user will uncheck the box, the hidden variable will have 0 as its value.
How are you marking them up?
I hope like this...
<input type="checkbox" name="something[]" value="55" />
Then in PHP...
if ( ! isset($_POST['something']) OR empty($_POST['something'])) {
echo 'Select a checkbox, please!';
}
You can also check with JavaScript...
var inputs = document.getElementById('my-form').getElementsByTagName('input');
var checked = 0;
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].getAttribute('type') !== 'checkbox') {
continue;
}
if (inputs[i].checked) {
checked++;
}
}
if (checked === 0) {
alert('Select a checkbox, please!');
}
See it working on JSbin.

how to uncheck checkboxes with javascript

I have the following code. I need to see how many checkboxes have been checked in my form and if there are more than four display error and uncheck the last check box,everything is working but how can I uncheck the last check box, thanks
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
I think that I would handle this differently. I'd have a click handler on each checkbox that counts the number of checked boxes (including the current if it is being checked) to see if it is greater than 4. If it is, then I would stop the current event, pop the alert, and reset the state of the checkbox causing the alert. This way it would always popup when clicking the fourth checkbox.
To handle the case where javascript is disabled, you'd need to make sure that your server-side code validates that no more than 4 checkboxes have been checked.
JQuery example:
$(':checkbox').click( function() {
if ($(this).val() == 'on') { // need to count, since we are checking this box
if ($(':checkbox:checked').length > 4) {
alert( "You can only choose up to a maximum of 4 toppings." );
$(this).val('off');
}
}
});
Note if you had other types of checkboxes on the page you could use a class to distinguish them. In that case, the selector becomes (':checkbox.topping') and (':checkbox.topping:checked').
Keep track of the last checked checkbox and set its checked property to false:
// ...
var lastChecked; // Will be used in loop below
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
lastChecked = i; // Store the checkbox as last checked
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
checks[lastChecked].checked = false; // Uncheck the last checked checkbox
} else {
// ...
If you want to uncheck all but the four first ones, do it like this:
// ...
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
if (totalChecked > 4) checks[i].checked = false; // Uncheck checkbox
}
}
Well you'll need to somehow pass into this method which particular checkbox was just checked, and then if the total checked count test fails, then just set that checkbox's .checked property to false.
What if the user checked more than five?
One way to do it is create a javascript function that returns false if more than four checkboxes are checked. In each checkbox, hook the new function like this:
<input type="checkbox" onclick="return myNewFunction(this);">
This will inhibit the user from checking any checkbox that is the fifth one.
Alternatively, you could prevent the user from making an invalid action in the first place, by disabling all the other boxes once four of them are checked, and displaying a message like "Choose up to four of these." This way, you don't let the user do something you know is invalid and then scold them.

Categories