Alert keeps popping up when on focus out - javascript

I have a grid in which user can add as many rows as he wants and there are two textboxes (Minimum Value & Maximum Value). When the user enters Min and Max value. I am checking whether the range that user has entered is already there in the database. if yes then it shows me an alert. I am doing this on focusout Now the problem is that the alert keeps popping up infinite times when I click from one textbox directly to another textbox. Can anyone help me with this?
Here is the function on my focus out
function CheckValidation(obj) {
var ajx = new AJAXsupport();
ajx.resetVar();
ajx.addData('CL', 'CheckValidation');
var sucSave = function() {
if (ajx.getRefreshText() != "0") {
alert(ajx.getMessage());
$('#btnSave').attr('disabled', 'disabled');
return false;
} else {
$('#btnSave').attr('disabled', false);
}
}
customSave(ajx, sucSave);
}
}

Related

Output Checked Items in Javascript Using Confirm()

I am trying to output the selected checked items from my list (I am using checkboxes) on the alert message on my page. Essentially, when the user hits the Delete button, I want a confirmation box to pop up and show the user which items they have selected to confirm it's correct (in this case, Serial Numbers). By default, all checkboxes are false (unchecked). If a checkbox is checked, the checkbox variable = true. Below is the function I wrote to do this:
function validateDeleteForm() {
var checkboxs=document.getElementsByName("pickSerial");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
}
}
if(okay)
{
if (confirm("Do you want to delete the selected Serial Number(s) from casting? Hit OK to Delete or CANCEL to re-select: " + this.checkboxs ) == true) { // this will delete selected serial numbers and display
return true;
}
//return true;
else { // this will cancel the delete dialogue and allow user to re-select
return false;
}
}
else {
alert("You have at least one line to be checked");
return false;
}
}
Does anyone see what I am doing wrong? I have tried referencing the checked items doing checkboxs[i].value, this.checkboxs[i], and calling the checkboxs variable but they all show as undefined.
Here is a screenshot of the output currently.
Thank you for any help.
Using querySelectorAll you can right away select all of the checked elements. There is no need to have to loop to find the check ones with this. You can then turn the html collection into an array to get all of the values. You can then use that array to display the info to the use.
const cbs = Array.from(document.querySelectorAll('[name="pickSerial"]:checked'));
const serials = cbs.map(function (cb) { return cb.value; });
if (serials.length) {
console.log(serials.join(",");
}
Adding to your solution, you can create an array to track checked items and then when printing, just use that array
Sample
const checked = [];
// When you are setting okay = true, push that value in checked
checked.push(checkboxs[i].value)
// Now when you are showing it in confirm box just join the array
confirm('text ' + checked.join(', '))
Hope that helps.

Preventing next tab if current tab have empty field

I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields

How to prevent a page from reload when an error occurs?

I am writing a code that takes the user input from a form, I've written a javascript code to check whether the fields in the form are empty or not. It is working well, but there is a problem that I've been trying to solve but I couldn't. If there is any empty field the error message occurs properly, but the page reloads immediately after that resetting everything. I've searched the web a lot and tried to return false in the javascript file, or even change the button type to "button", but nothing worked.
Here is the submit button code which is written inside a form,
<input type="submit" value="Update" name="Update" class="submitbutton" >
Here is the javascript file that's used for validation,
var emptyfields=0;// to count the errors
function init()
{
var myForm = document.getElementById( "myForm" ); //calling forms by ID
emptyfields=0;
myForm.onsubmit = check;// if the admin click submit (check function will be called)
myForm.onreset = clear;// if the admin click clear (clear function will be called)
} // end function init
function check()
{
if(document.getElementById("name").value=="")//check if the name filed is empty
{
document.getElementById("invalid_name").innerHTML="You must fill the Name field";
document.getElementById("name").style.borderColor="red";//change the color of the border's filed into red
emptyfields+=1;//increment it to count the error
}
else
{
document.getElementById("invalid_name").innerHTML=""; //set the error message to empty
document.getElementById("name").style.borderColor="black";//return the original border's filed color
}
if(document.getElementById("quantity").value=="") //check if the quantity field is empty
{
document.getElementById("invalid_quantity").innerHTML=" You must fill this field with a number"; //show the quantity error message
document.getElementById("quantity").style.borderColor="red"; //change the boarder color of quantity filed to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_quantity").innerHTML=""; //set the quantity error message to "" in order to hide it
document.getElementById("quantity").style.borderColor="black"; //reset the border of the quantity field to black
}
//check if the price field is empty
if(document.getElementById("Price").value=="")
{
document.getElementById("invalid_price").innerHTML=" You must fill this field with a number"; //show the price error message
document.getElementById("Price").style.borderColor="red"; //change the border color of price field to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_price").innerHTML=""; //set the price error message to "" in order to hide it
document.getElementById("Price").style.borderColor="black"; //reset the border color of the price field to black
}
if(document.getElementById("image2").value=="") //check if the image field is empty
{
document.getElementById("invalid_image").innerHTML=" You must upload an image"; //show the image error message
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_image").innerHTML=""; //set the image error message to "" in order to hide it
}
if(document.getElementById("Description").value=="") //check if the description field is empty
{
document.getElementById("invalid_Description").innerHTML=" You must fill the Description field"; //show the description error message
document.getElementById("Description").style.borderColor="red"; //change the border color of description field to red
emptyfields+=1; //increment the number of errors
}
else
{
document.getElementById("invalid_Description").innerHTML=""; //set the description error message to "" in order to hide it
document.getElementById("Description").style.borderColor="black"; //reset the border color of the description field to black
}
if (emptyfields >0) //check if there is any input error made by the user
{
return false; //if yes return false
}
else
{
return true; //if no return true
}
}//the end of the check function
function clear()
{
return confirm( "Are you sure you want to reset?" ); //ask the user if she is sure about resetting the fields.
}
window.addEventListener( "load", init, false ); //add a load event listener to the window which triggers init function that calls check and clear functions to perform the validation and reset
can anyone please tell me how to prevent the page from reloading?
Any help is highly appreciated.
Thank you.
The onsubmit callback is called with an event argument which can be used to stop the event triggering its default behaviour. Change your code to:
function check(e) {
// your validation code ...
if(error) {
e.preventDefault();
}
}
You can find out more here.
This is often more desirable than using return false for reasons that are summed up in this answer
You need to return false; by check(). So when an error occurs, it prevents onsubmit from submitting the form.
ie.
myForm.onsubmit = check();
// short version of check
function check() {
...
if(error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
Hope this helps.

Checking my users input is a number of a set length?

Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks
this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.

disabling submit button till input fields are validated

i have disabled the submit button in my guestbook. it has 2 fields[name(textbox)&comment(textarea)].it has 2 other fields ID(primary key) and date.the function is:
function Frmvalidate() {
var nmchk=document.forms["guestform1"]["name"].value;
var cmntchk=document.forms["guestform1"]["comment"].value;
if (nmchk.length==0)
{
var namep = document.getElementById("namep");
namep.innerHTML="name must be filled out";
return false;
}
else if (cmntchk.length==0)
{
var cmntp = document.getElementById("cmntp");
cmntp.innerHTML="comment must be filled out";
return false;
}
else
{
document.getElementById("sbmt").disabled=false;
return true;
}
}
i have called the function in places: body tag's onload,button tag's onclick. still its not working and blank entries are being stored in my database.
You dont need to disable the submit button
you gain noting from it. ( alerting the user , running another script etc...)
instead -- The submit button should stop its regular behaviour by this code :
<input type="submit" onclick="return Frmvalidate();"/>
meaning :
when you press the button , it will execute the function yielding True or False and if it's True (only) it will continue to the server.

Categories

Resources