I have code below.
The code works fine, but if I uncomment the "if" statement, alert will show up as soon as I enter something to input field.
I want the "sum" value to be checked (alert shows up) only after I entered all 3 input fields.
Please help me to fix it. Thanks.
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val1__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val2__c}" />
<apex:inputField styleClass="Weight" value="{!EvaluationInformation__c.val3__c}" />
$(document).ready(function() {
$(document).on("input", ".Weight", function(e) {
var sum = 0;
$('.Weight').each(function() {
var num = $(this).val();
if (num != null && !isNaN(num)) {
sum += parseFloat(num);
} else {
alert("Accept number only");
}
});
//if (sum != 1){ // sum !=1 doesn't work
// alert("The total of Weight must be 1");
//}
});
});
You can use a status flag that will tell if all inputs are valid, see my example code below.
Also, AFAIK val() for an <input> element never returns null, it returns "" if there is no input. This is why I used if (num && ... instead, which in this situation means "only proceed if num contains text".
$(document).ready(function() {
$(document).on("change", ".Weight", function(e) {
var sum = 0;
var allInputsValid = true; // <-- flag variable
$('.Weight').each(function() {
var num = $(this).val();
if (num && !isNaN(num)) {
sum += parseFloat(num);
} else {
allInputsValid = false;
}
});
if (allInputsValid) {
console.log("All inputs have numbers.");
if (sum != 1) {
console.log("The total of Weight must be 1, but it is: " + sum);
} else {
console.log("The total of Weight is 1.");
}
} else {
console.log("Not all input have numbers yet.");
}
});
});
.Weight { width: 50px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
#1: <input class="Weight" /> #2: <input class="Weight" /> #3: <input class="Weight" />
PS - Even then, you may have trouble making this work because of how Floating Point math works. Due to internal rounding, a sum of numbers that you would expect to be 1 will not always produce exactly 1:
var x = parseFloat("0.34") + parseFloat("0.56") + parseFloat("0.10");
console.log(x);
console.log(x === 1);
Related
On a javascript homework assignment for my javascript class, the assignment requires a ".js" for loop iteration to list the names of the pets a user inputs (3 is the limit).
There are three horizontally spaced text-input boxes and regardless of what text boxes the user inputs pet names into, the "message" (id) output below the submit button will display pets' names inputted up to the limit imposed by the user (<= 3). Once the pets' names are inputted and submit button clicked, the page will display the pets' names starting from the left most text box the user has inputted in and going towards the right, until the user's chosen input limitation (<= 3) has reached its limit; therefore, if a user selects 2 as the limitation, only the left-most text boxes with pet names inputted will be displayed below the submit button.
So far I have tried referring to the pet id's and pet names as memberid ('pet' + 'cntr'), membername, and together in the for loop iteration they are given the id of members += membered + membername;
if (myNumPets == '' || myNumPets > 3) {
$('numpets_error').innerHTML = " Please enter the number of
pets you have ";
myTruth = true;
} else {
if (myNumPets < '4') {
$('numpets_error').innerHTML = "";
myTruth = false;
}
}
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
cntr = '';
members = "";
for (cntr = 1; cntr <= myNumPetsEntered; cntr++) {
var memberid = "pet" + cntr;
console.log("MID " + memberid);
var membername = $(memberid).value;
members += memberid + membername;
}
$('message').innerHTML = members;
In this present code, when the number limitation is '1', only the first input box displays the inputted pet's name in the 'message' area below the submit button; however, I would like the inputted pet's name to appear there regardless of whether the inputted pet's name is in the first and left-most input box or one of the two that are to the right of it, and I want the same to be true of the other number limitations (2 and 3).
In your for loop you're just blindly grabbing the value of N text inputs, where N = myNumPetsEntered.
If myNumPetsEntered == 1 and you've typed the pet's name into the second input box, the loop will never see that value. You'll want to do some validation to make sure you've actually grabbed a value.
I don't know how involved this homework assignment is, but you might also be interested in validating whether or not the number of text boxes with values is at least equal to (or greater than) the number of pets names the user said they were going to input.
You can also clean up those nested if statements - assuming you've got logic in place preventing myNumPets from being a negative value, you could just use:
if (myNumPets <= 3) {
myNumPetsEntered = myNumPets;
}
For a start, this chunk code can be cleaned up a lot. The current logic is messy. Just imagine if the limit was 8 instead of 3.
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
My suggestion is to change to a range like this:
if ((myNumPets >= 0) && (myNumPets <= 3)) {
myNumPetsEntered = myNumPets;
}
To be honest, I am trying to make sense of the rest of the question. Think you are after something like the following:
var petCount = 0;
function petAdd(e) {
// stop the default button function
e.stopPropagation();
e.preventDefault();
// make sure only 3 pet names are entered.
if (petCount >= 3) {
alert("There is a max of 3 pet names");
return;
}
// do we have a new pet name?
var pet = document.getElementById("petNameInput");
if ((pet.value) && (pet.value.trim())) {
// we do have a name, add the name to the display
var displayName = document.getElementById("petNameDisplay");
// is it the first name?
if (petCount == 0) {
displayName.textContent = "My pet name(s) are: "+ pet.value.trim();
} else {
displayName.textContent += ", "+ pet.value.trim();
}
// keep track of the number of names
petCount++;
// clear the old name, ready for the next
pet.value = "";
}
// have we reached 3 names yet? if so, remove the input
if (petCount >= 3) {
var petRow = document.getElementById("petNameRow");
if (petRow) {
petRow.style.display = "none";
}
}
}
// add the method call when the button is pressed
window.onload = function() {
var d = document.getElementById("petAddButton");
if (d) {
d.addEventListener("click",petAdd,false);
}
}
What are you pets' names? <i>max of 3</i><br />
<div id="petNameRow">
<input type="text" id="petNameInput" placeholder="Enter a name here" />
<button id="petAddButton">Add pet</button>
</div>
<div id="petNameDisplay"></div>
Just an observation: This entire block is unnecessary. Why not just myNumPetsEntered = myNumPets? Or better yet, eliminate myNumPetsEntered altogether and use myNumPets in the loop?
if (myNumPets == 0) {
myNumPetsEntered = 0;
} else {
if (myNumPets == 1) {
myNumPetsEntered = 1;
} else {
if (myNumPets == 2) {
myNumPetsEntered = 2;
} else {
if (myNumPets == 3) {
myNumPetsEntered = 3;
}
}
}
}
Anyway. Here's one way to do it. Not sure it satisfies the requirements of your homework assignment, but then I shouldn't be doing your homework anyway.
function onButtonClick () {
// get the pet name inputs
const inputs = document.querySelectorAll('input[name=petname]');
// get the max names value
const max = document.querySelector('input[name=max]').value;
const names =
Array.from(inputs.values()) // convert the 'inputs' NodeList to an array
.map(i => i.value.trim()) // extract the value of each input and strip white space
.filter(Boolean) // filter out anything 'falsy' to eliminate empty values
.slice(0, max); // chop off anything beyond the max number
// string the values together, separated by a comma, and insert the result into the message box.
document.getElementById('message').innerHTML = names.join(', ');
}
label, button {
display: block;
}
input {
margin: 1rem 0;
}
<div>
<label>Number of Pets: <input type="number" min="1" max="3" name="max" value="3" /></label>
<input name="petname" />
<input name="petname" />
<input name="petname" />
<button onClick="onButtonClick()">Go.</button>
<div id="message" />
</div>
What I try to achieve to give alert if the sum of first values are greater than 100 if not third value has to be calculated like this;
3th textbox= 100- 1st textbox- 2th textbox
It works well at the beginning. When I type 100 for 1st textbox then 20 for 2nd I get error then I enter 80-30 I get again alert but then third times when I enter 50-30 I again get error but actually it shouldnt give error it should write in third textbox 20
$(document).ready(function() {
// calc
jQuery("#custom-419").on("change", function() {
var vorOrt = $(this).val();
jQuery("#custom-420").on("change", function() {
var vorOrt2 = $(this).val();
var sum = 0;
sum += parseInt(vorOrt);
sum += parseInt(vorOrt2);
console.log($('#sum').val());
if (sum <= 100) {
var onWeb = 100 - vorOrt;
onWeb = onWeb - vorOrt2;
jQuery("#421").val(onWeb);
} else {
window.alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
}
});
})
});
Because all the other answers contains jQuery, I though it may be helpful to provide a vanilla JavaScript solution. Keep in mind that solution is for modern browser only!
function calc() {
const counters = [...document.querySelectorAll('.counter')];
const total = document.querySelector('.total');
const sum = counters.reduce((a, b) => a += parseInt(b.value) || 0, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
counters.forEach(x => x.value = '');
total.value = '';
}
[].forEach.call(document.querySelectorAll('.counter'), x => x.addEventListener('keyup', calc));
<div>
result has to be less then or equal 100
</div>
<input class="counter" id="#custom-419" /> +
<input class="counter" id="#custom-420" /> =
<input class="total" id="#custom-421" disabled />
Explanation
Because you didn't show us your current html, I made it simple. So no explanation required I guess.
What happens in that JS solution is pretty straight forward.
In the last line both input with the call counter are getting an EventListener to fire on keyup. You may keep the change event instead...
In the calc function all values of the counters get parsed to int and aggregated to sum. The rest of the code is nothing special.
As the above solution is for modern browsers only (ES6+), here are two more for older browsers:
IE11+ Support (Demo)
function calc() {
const counters = document.querySelectorAll('.counter');
const total = document.querySelector('.total');
const sum = Array.prototype.reduce.call(counters, function(a, b) {
return a += parseInt(b.value) || 0;
}, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
Array.prototype.forEach.call(counters, function(x) {
x.value = '';
});
total.value = '';
}
Array.prototype.forEach.call(document.querySelectorAll('.counter'), function(x) {
x.addEventListener('keyup', calc);
});
IE9+ Support (Demo)
I made two more function for this example to make it a bit more readable.
function calc() {
var counters = document.querySelectorAll('.counter');
var total = document.querySelector('.total');
var sum = getSum(counters);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
clearCounters(counters);
total.value = '';
}
function getSum(counters) {
var result = 0;
for(var i = 0; i < counters.length; i++) {
result += parseInt(counters[i].value) || 0;
}
return result;
}
function clearCounters(counters) {
for(var i = 0; i < counters.length; i++) {
counters[i].value = '';
}
}
var _counters = document.querySelectorAll('.counter');
for(var i = 0; i < _counters.length; i++) {
_counters[i].addEventListener('keyup', calc);
}
Why nesting the 2 event functions ?
Try this :
var vorOrt = 0;
var vorOrt2 = 0;
$(document).ready(function() {
$('#custom-419').on('change', function() {
vorOrt = $(this).val();
checkInputs();
});
$('#custom-420').on('change', function() {
vorOrt2 = $(this).val();
checkInputs();
});
});
function checkInputs() {
var sum = 0;
sum += parseInt(vorOrt, 10);
sum += parseInt(vorOrt2, 10);
if (sum <= 100) {
var onWeb = 100 - vorOrt - vorOrt2;
$("#custom-421").val(onWeb);
} else {
window.alert('The sum of values can not be more than 100!');
$('#custom-419').val('');
$('#custom-420').val('');
$('#custom-421').val('');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />
Once change function is inside the other, which is not necessary, Also reset the value of sum when alert is thrown
$(document).ready(function() {
var sum = 0; // initializing sum
function calSum(val) {
sum += val; // will add the values
console.log(sum)
if (sum <= 100) {
var onWeb = 100 - sum;
$("#custom-421").val(onWeb);
} else {
alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
sum = 0;
}
}
$("#custom-419").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
$("#custom-420").on("change", function() {
calSum(parseInt($(this).val(), 10));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="custom-419">
<input type="text" id="custom-420">
<input type="text" id="custom-421">
Look at the following solution. It uses jQuery's each.
What I did is attach the same function to every input by using a descriptive class name: counter. We can easily get all the input using the selector input.counter and add an onchange event with only one line of code.
After that the generic function testIfMoreThanHundred will iterate over all the element using each and sum the values into a variable.
after that it's just a simple if check to see if the value if more than a hundred.
$(document).ready(function() {
// calc
$("input.counter").on("change", testIfMoreThanHundred);
});
//let's make a generic function shall we:
function testIfMoreThanHundred() {
var sum = 0;
//get the elements and use each to iterate over them
$("input.counter").each(function() {
var number = parseInt($(this).val(), 10);
//test if value is a number, if not use 0
if (!isNaN(number)) {
sum += parseInt($(this).val(), 10);
} else {
sum += 0;
}
});
if (sum > 100)
{
alert("The sum can't be greater than a 100");
$("input.counter").val(""); //empty the values
$("input.total").val("");
}
else
{
$("input.total").val(100 - sum); //show value in third box
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="counter" id="custom-419" type="number" />
<input class="counter" id="custom-420" type="number" />
<input class="total" id="custom-421" type="number" />
I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}
I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.
I want to produce a validation message in an alert for when any text input within a question is empty. So for example if I have 2 blank text inputs for question 1, if both text inputs are blank, it displays the validation message You have not entered in a value in all the Indivdiaul Marks textbox.
But the problem is that for question 1 for example, if 1 text input is blank but the other is not blank, it does not display the validation message, even though it should do as not all text inputs have been filled for question 1.
My question is that how can I get the validation message to appear if there is any blank text input per question?
Here is a fiddle so you can test it: http://jsfiddle.net/cbyJD/87/
Below is the validation() function code:
function validation() {
// only keeping track of the final message
var alertValidation = "",
// toggle for showing only one error
showOnlyOneError = true;
$("input[data-type='qmark']").each(function(i) {
var questions = $(this).attr("data-qnum");
var marks = parseInt($("[class*=q" + (i+1) + "_ans_text]").text());
var txtinput = $(this).val();
// the message for this question
var msg = '';
if (txtinput == '') {
msg += "\n\u2022 You have not entered in a value in all the Indivdiaul Marks textbox \n";
}
if (marks < 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Need To Remove " + Math.abs(marks) + " Marks";
} else if (marks > 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Have " + marks + " Marks Remaining";
}
// if there is an error for the question, add it to the main message
if (msg.length) {
alertValidation += alertValidation.length ? '\n\n' : '';
alertValidation += "You have errors on Question Number: " + questions + "\n";
alertValidation += msg;
// stop if we only care about the first error
return !showOnlyOneError;
}
});
// show the error messages
if (alertValidation != "") {
alert(alertValidation);
return false;
}
return true;
}
First, add a hidden variable num_groups with the total number of groups.
<p>
<input type='hidden' id='num_groups' name='num_groups' value='2'>
<input id="submitBtn" name="submitMarks" type="submit" value="Submit Marks" />
</p>
Second, change the validate function to work on a single group of questions:
function validation(group) {
var msg = [];
var nb = 0; // Number of blank values
$("input[data-qnum='" + group + "']").each(function() {
if ($(this).val() == '') {
nb++;
return false;
}
});
if (nb != 0) {
msg.push("\u2022 You have not entered in a value in all the Individual Marks textbox");
}
var marks = parseInt($("[class*=q" + group + "_ans_text]").text());
if (marks != 0) {
msg.push("\u2022 Your Total Marks Remaining does not equal 0");
if (marks < 0) {
msg.push("- You Need To Remove " + -marks + " Marks");
} else if (marks > 0) {
msg.push("- You Have " + marks + " Marks Remaining");
}
}
if (msg.length > 0) {
alert("You have errors on Question Number: " + group + "\n\n" + msg.join("\n"));
return false;
} else {
return true;
}
}
Third, change the myClickhandler function to validate all the groups:
myClickHandler = function(e) {
var ng = $('#num_groups').val();
for (var group = 1; group <= ng; group++) {
if (!validation(group)) return false;
}
if (confirm("Are you sure you want to Proceed?")) {
$.ajax({
url: "insertmarks.php",
data: $("#markstbl").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
}
JsFiddle here.
The validation() function returns true no matter what it finds.
You need to declare a variable at the top of this function called errors or similar, with a value of false. For everywhere in the function that an error is found, set the value of errors to true.
At the close of the function with...
return !errors; // return the value of errors NOT'ed
Then you call call validation() in a test, like so...
if (validation()) {
// everything is groovy
} else {
// make them do the form over, or something
}