How to show alert message using javascript to check checkbox? - javascript

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!!!')

Related

Boostrap javascript form validation

I doing a bootstrap and javascript form validation. What I am checking is if the form was filled out or not. One the form I left the two radio buttons uncheck, when I submit the form the warning message comes up and says that you must select an option. When I select an option and click on submit it doesn't submit he form. I've implemented the code below and so far the code is showing the warning message that the form wasn't completed.
/****** Checks to see if the form is filled out
****************************************************** */
function validateForm() {
var radios = document.getElementsByClassName(".form-check-input");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked){
formValid = true;
i++;
}
}
if (!formValid){ $("#modalButton").click(function(){
$("#buttonAlert").addClass('show') //Shows Bootstrap alert
});
return formValid;
}
else{
return true;
}
}
what am I doing wrong or missing?
The formValid rule must be within the click event:
function validateForm() {
var radios = document.getElementsByClassName(".form-check-input");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) {
formValid = true;
i++;
}
}
if (!formValid) {
$("#buttonAlert").addClass('show')
return formValid;
} else {
return true;
}
}

Submit form only if all required fields are full?

I want to do form.submit() but only if all form items with the required attribute are full.
I was thinking on simpy iterating through the form children in search for the attribute, but I'm not sure how to do it since there might be nested elements and such. And probably there is an easier way to do it.
this.form_is_full = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].getAttribute("required") && form.elements[i].value=="")
{
// If has attribute required and is blank return false
}
}
return true;
}
How can I do this?
function Validate()
{
// create array containing textbox elements
//for example:
var inputs = [document.getElementById('fname'),
document.getElementById('lname'), document.getElementById('email'),
document.getElementById('messagetxt')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
Try this:
$('#YourFormId').submit(function(e) {
if ($.trim($("#YourFormId input").val()) === "") {
e.preventDefault();
alert('you did not fill out one of the fields');
}
});
This is what I did:
this.validate_form = function(form){
for (var i = 0; i < form.elements.length; i++){
if(form.elements[i].value == "" && form.elements[i].getAttribute("name") && form.elements[i].hasAttribute("required"))
{
return false;
}
}
return true;
}

How Would I Alter This Javascript Code to validate the data

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;
}
}

Form Validation - How to use If and Else If

I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...

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