How Would I Alter This Javascript Code to validate the data - javascript

What would I need to add in order for this to validate according to how many checkboxes have been selected? I want the user to select at least two checkboxes before submission of data. Here is my Javascript code:
<script type="text/javascript" language="JavaScript">
function checkCheckBoxes(theForm) {
if (
theForm.Conservatives.checked == false &&
theForm.Labour.checked == false &&
theForm.LiberalDemocrats.checked == false)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}
</script>
The current Javascript code only validates if any checkboxes have been selected or not, but I want it to validate for two checkboxes.

Just count how many are checked and see if it's less than 2.
function checkCheckBoxes(theForm) {
var cnt = 0;
if (theForm.Conservatives.checked) ++cnt;
if (theForm.Labour.checked) ++cnt;
if (theForm.LiberalDemocrats.checked) ++cnt;
if (cnt < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}

As long as you're only worried about those three checkboxes and you don't want to use a JavaScript library, the easiest thing I can think of would be:
var checkedBoxes = [];
if(theForm.Conservatives.checked)
checkedBoxes.push(theForm.Conservatives);
if(theForm.Labour.checked)
checkedBoxes.push(theForm.Labour);
if(theForm.LiberalDemocrats.checked)
checkedBoxes.push(theForm.LiberalDemocrats;
// two or more boxes are checked
if(checkedBoxes.length < 2){
alert('Choose at least two parties.');
}
else {
// Do stuff with checkedBoxes.
}
This method will not only give you the Count of the number of checked items but will also allow you to access only the checked boxes later in your code if needed.

You can do:
if (theForm.Conservatives.checked +
theForm.Labour.checked +
theForm.LiberalDemocrats.checked) < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}

function checkCheckBoxes(theForm) {
var opts = ["Conservatives","Labour","LiberalDemocrats"],
selected = 0;
for (var i = 0; i < opts.length; i++) {
if (theForm[opts[i]].checked)
selected++;
}
if (selected < 2) {
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}

function checkCheckBoxes(theForm) {
if(theForm.Conservatives.checked + theForm.Labour.checked + theForm.LiberalDemocrats.checked > 1)return true;
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
}

function checkCheckBoxes(theForm) {
var checkboxes = [theForm.Conservatives, theForm.Labour, theForm.LiberalDemocrats];
var checked = 0;
checkboxes.forEach(function(el){
if (el.checked) checked++;
});
if (checked < 2)
{
alert ('Choose At Least Two Parties Who Will Be Standing For This Election');
return false;
} else {
return true;
}
}

Related

Validating Radio entry

I have 2 address entries on my form. I also have 2 radio buttons to designate the "preferred" mailing address.
I'm attempting to validate these 2 and am not really sure if I'm doing it correctly. It seems to work if I have both addresses filled but I can't seem to get it to validate correctly if one of the addresses isn't filled.
Here's the javascript that does the validation:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
$("#" + prefs[i]).prop('checked', false);
$("#MailPrefBusi").validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
$("#MailPrefBusi").validationEngine({promptPosition : "bottomRight", scroll: true}).validationEngine('showPrompt', 'You must select the correct Mailing Preference', 'error', true);
return false;
}
}
return true;
}
I'm using jQueryValidationEngine but it also doesn't correctly validate them. I only use it to show the validation error for these fields.
Here is the criteria:
If the MailPrefBusi is checked, then the BusinessAddress1 must be filled in.
If the MailPrefHome is checked, then the HomeAddress1 must be filled in.
If no MailPrefxxx is checked, show error. If no xxxAddress1 is filled, Show error.
It looks like your second if statement if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) { is returning false when you don't want it to. You should be able to accomplish what you want using this:
function checkMailingPrefs() {
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
for (i = 0; i < 2; i++) {
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "") {
// enhanced validation function call here
return false;
}
}
//if the user hasnt checked anything, you can remove this if the form should validate without the user having to set a radio button
if(!$("#MailPrefBusi, #MailPrefHome").is(":checked")) {
// enhanced validation function call here
return false
}
return true;
}
You can see it working at this JS Fiddle: https://jsfiddle.net/h0vj9r35/
Hope that helps!
If you are trying to figure out whether the corresponding fields are filled based on checkbox values in a scenario where you have n no. of checkboxes and fields and would like to avoid hardcoding of values, you may use the following:
var prefs = ["MailPrefHome", "MailPrefBusi"];
var field = ["HomeAddress1", "BusinessAddress1"];
var allEmpty = false;
var valueError = ""
for (i = 0; i < 2; i++)
{
if ($("#"+field[i]).val() == "" || !$("#"+prefs[i]).is(":checked")) {
if(!$("#"+prefs[i]).is(":checked"))
valueError += prefs[i] + "," ;
else if($("#"+field[i]).val() == "")
valueError += field[i];
allEmpty = true;
}
if ($("#"+prefs[i]).is(":checked") && $("#"+field[i]).val() == "")
{
$("#" + prefs[i]).prop('checked', false);
allEmpty = false;
alert("Need to enter " + field[i]);
return false;
}
if((i == 1) && allEmpty)
{
alert("You need to select " + valueError);
return false;
}
}
return true;
http://jsfiddle.net/n0303qd6/1/

How to show alert message using javascript to check checkbox?

I am using following code to detect whether the check box inside my gridview template field is checked or not. If none of the check box is selected then I want to show alert message.
function findCheckBox() {
var inputElements = document.getElementsByTagName('input');
var chekSelect = false;
for (var i = 0; i < inputElements.length; i++) {
var myElement = inputElements[i];
if (myElement.type === "checkbox") {
if (myElement.checked === false) {
chekSelect = true;
return true;
}
}
if (chekSelect === true) {
return true;
}
else {
alert('Please Check Atleast one record to print cheque!!!');
return false;
}
}
}
But with this code when I click on my button its showing me error message for one time even if one or more check box is checked. What I am doing wrong here. Can anyone help me please.
Your logic is slightly off. Corrected version:
jsFiddle demo
function findCheckBox() {
var inputElements = document.getElementsByTagName('input');
var chekSelect = false;
for (var i = 0; i < inputElements.length; i++) {
var myElement = inputElements[i];
if (myElement.type === "checkbox") {
if (myElement.checked) {
chekSelect = true;
break;
}
}
}
if(!chekSelect) {
alert('Please Check Atleast one record to print cheque!!!');
return false;
} else {
return true;
}
}
I've changed the .checked test, to test for it being true not false, because you want to know if at least one checkbox is checked. I also added a break, and moved the alert to outside of the for, because you won't know if there is a checkbox checked until the for completes.
Try this
function findCheckBox() {
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
var myElement = inputElements[i];
if (myElement.type === "checkbox" && myElement.checked) {
return true;
}
}
alert('Please Check Atleast one record to print cheque!!!');
return false;
}
Using JQuery:
var checked = false;
$('input:checkbox').each(function(){
if($(this).prop('checked')){
checked = true;
break;
}
});
if(!checked) alert('Please Check At least one record to print cheque!!!')

What is the JavaScript code for validating a form, getting elements by name, with a loop?

I have read between 5 & 7 posts, have tried to play with some of the things I have read, including jQuery, but it feels as though most posts are well beyond my understanding.
I have a form which will act as a data submission tool, so let's say 100 inputs.
I just need help checking each input, and I figured that I should be able to do it using a loop.
Goal code example:
function ()
{
for (i = 1; i < 101 ; i++);
var c = document.getElementsByName("Input_row_" [i]);
if ( c = some conditionals here )
{
alert("message");
return false;
}
}
For a specific argument, one of the things I need to check is that there are no spaces in the input:
function ()
{
for (i = 1; i < 101 ; i++);
var c = document.getElementsByName("Input_row_" [i]);
if ( c = "" )
{
alert("message");
return false;
}
}
Can anyone help with my syntax or get me further towards the goal?
Thanks.
-It goes without saying that I am not a programer by trade, so simple explanations would be great.
Method 1
function validate() {
for (var i = 1; i < 101 ; i++) {
var c = document.getElementsByName("Input_row_"+i)[0].value;
if (c == "" ) {
alert("Please fill in #"+(i+1));
return false;
}
}
return true;
}
Method 2
function validate(theForm) {
var elements = theForm.elements;
for (var i = 1; i < elements.length ; i++) ( // no need to know how many
if (elements[i].name.indexOf("Input_row")!=-1 && elements[i].value == "" ) {
alert("Please fill in "+elements[i].name);
return false;
}
}
return true; // allow submit
}
using <form onsubmit="return valdiate(this)"..
Without inline code:
window.onload=function() {
document.getElementById("formID").onsubmit=function() {
var elements = this.elements;
for (var i = 1; i < elements.length ; i++) ( // no need to know how many
if (elements[i].name.indexOf("Input_row")!=-1 && elements[i].value == "" ) {
alert("Please fill in "+elements[i].name);
return false;
}
}
return true; // allow submit
}
}

How to change this IF to allow selection between two numbers only?

I am using a jQuery script and the main part is below. It allows me to select up to 4 items. Until there are 5 selections made, there is an error message.
How can I change this so that the error message appears if the choices are less than 2 and more than 5, and the success message is shown when the choices are between them?
if ($(this).multiselect("widget").find("input:checked").length > 5) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
You can get the number of checked items in to a local variable and then use a compound if statement that does multiple comparisons on it:
var checkedItemsLength = $(this).multiselect("widget").find("input:checked").length;
if(checkItemsLength < 2 || checkItemsLength > 5 ) {
warning.addClass("error").removeClass("success").html("You can only check two checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
function doSomeChecking() {
// assuming 'warning is a reference to some div or span
var warning = $('#warning');
var numChecked = $(this).multiselect("widget").find("input:checked").length;
if (numChecked > 5) {
warning.addClass("error").removeClass("success").html("You cannot check more than five boxes!");
return false;
} else if (numChecked < 2) {
warning.addClass("error").removeClass("success").html("You must check at least two boxes.");
return false;
}
warning.addClass("success").removeClass("error").html("Life is good.");
return true;
}
var selections = $(this).multiselect("widget").find("input:checked");
if(selections.length < 2) {
warning.addClass("error").removeClass("success").html("You have to check atleast two checkboxes!");
return false;
} else if (selections.length > 5) {
warning.addClass("error").removeClass("success").html("You can not check more then five checkboxes!");
return false;
} else {
warning.addClass("success").removeClass("error").html("Check a few boxes.");
}
if(foo < 2 || foo > 5){
//do something
}else {
//do something else
}

Checkbox validation - at least one selected

I have number of checkboxes and another checkbox for "Select All"
I want to check if the user has selected at least one checkbox. Need modification in javascript
<script language="Javascript">
function doSubmit(){
function check_checkboxes()
{
checked=false;
var c = document.getElementsByTagName('INPUT');
for (var i = 1; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {
return true}
else {alert("Please identify what warehouses comply:"); }
}
} //if I place my struts action here..its not working?
}
document.holiDay.command.value= 'addingApp'; //My Struts action if something checked.
document.holiDay.submit();
}
var all=document.getElementById('holiDay');
In HTML IDs should be unique, so getElementById will only return 1 element. Perhaps you could try getElementsByTagName - http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx ?
Something like...
function check_checkboxes()
{
var c = document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++)
{
if (c[i].type == 'checkbox')
{
if (c[i].checked) {return true}
}
}
return false;
}
and change your Validate function to...
function Validate()
{
if(!check_checkboxes())
{
alert("Please identify what warehouses comply:");
return false;
}
return true;
}
Select at least one check box using jqQery. Try the following code.
$('input[type="checkbox"][name="class"]').on('change', function () {
var getArrVal = $('input[type="checkbox"][name="class"]:checked').map(function () {
return this.value;
}).toArray();
if (getArrVal.length) {
//execute the code
} else {
$(this).prop("checked", true);
alert("Select at least one column");
return false;
}
;
});
(function() {
for(x in $ = document.getElementsByTagName("input"))
with($[x])
return (type == "checkbox" ? checked == true : 0)
})

Categories