How to hide an image on blank form submission? - javascript

I have an image that is kind of a spinner that is displayed to a user on submitting a form.
So in js.coffe I do something like this:
$('.button.save-btn.btn.btn-primary').click ->
$('.loader').show()
And if the form fails validations and an error is shown, at that time I hide the same image, like this:
$('#error-box').show();
$('.loader').hide();
The spinner works fine when an error is encountered but now what if when the user is clicking on the submit button when the form is empty. How do I handle that event? Where exactly do I hide the spinner image in this case?
I hope I explained my query properly, any help will be much appreciated. Thanx in advance:)

I don't use coffee personally but in plain js you could check if the fields have a value before showing the spinning image:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = false;
//iterate trough each input field
$("#MyformID").find("input, textarea").each(function(){
//check if input field has a value or is empty
if ($(this).val() != ""){
form_compiled = true;
}
})
// and then show the image if at least a filed is filled
if ( form_compiled == true){
$('.loader').show()
}
})

the code above works if the user fills at leas a field.
If you want to run the check on just some mandatory fields you could add them the class "required", for example, then run the js check on those classes:
$('.button.save-btn.btn.btn-primary').click(function(){
var form_compiled = true; << change initialization
$("#MyformID").find(".required").each(function(){
//check if input field is empty
if ($(this).val() == ""){
form_compiled = false; //set to false is a required field is empty
}
})
if ( form_compiled == true){
$('.loader').show()
}
})

Related

how to keep validation off if some section of forms not showing during form-filling in jquery

how to keep validation off if some section of forms not showing during form-filling in jquery. as
function formsubmit(){
var ammount = $('#ammount').val();
var emp_status = $("input[name='empstatus']:checked").val()?$("input[name='empstatus']:checked").val():'undefined';
var com_name = $('#com_name').val();
var ann_inc=$('#ann_inc').val();
var city=$('#city').val();
var emi_paid = $("input[name='emi_paid']:checked").val()?$("input[name='emi_paid']:checked").val():'undefined';
flag = true;
if (ammount.trim()=='') {
$('#msgammount').css('color','red');
$('#msgammount').text('Please Enter Price');
$('#msgammount').show();
return false;
}
if (emp_status == 'undefined') {
$('#msgempstatus').css('color','red');
$('#msgempstatus').text('Please Enter Price');
$('#msgempstatus').show();
return false;
}
if (emi_paid == 'undefined') {
alert('undefined');
return false;
}
}
I want to hide the error emi_paid section as some of the user not going to fill emi_details if they will not took any loan from bank, so i am using radio button if user has any existing loan then only emi option appear,
my code run well the only thing disappoint me to hide the emi_paid error, it will show always at the time of form submission.
Why not use validation js Like validate.js or jQuery.validationEngine v2.6.2.These validation are easy to use as well as these validation has a setting to turn on or off validation for hidden element according to your requirement.
Hidden validation for hidden elements in form submit
$.validator.setDefaults({
ignore: ":hidden"
});
I highly recommend your to use these.

Controlling the submission

I'm trying to stop the submit if an error exists and go through the submission if no error exist.
This is just a section of the code. Regex works correctly, also the error texts were showing up too. The thing is that now I'm trying to control the submit proccess and due to an error (console is not showing up anything) the error text is not showing up and the submission is just going through even if an input error exists.
There is a mistake that I cannot figure out (No jquery please)
var sub = document.querySelector("#register input[type='submit']");//the submit botton
var err_text_1 = "First name must be filled out!";
sub.onsubmit = function(){
if (first_name == null || first_name == "") {
err_holder_1.innerHTML = err_text_1;
return false;
}
else {
err_holder_1.style.display = "none";
}
}
To prevent submit add event in the function and return false like so:
sub.onsubmit = function (event) {
// Will prevent submit
event.preventDefault();
return false;
};
Also select the form you are submitting not the button itself. So:
var sub = document.getElementById('ActionForm');
Hope this helps.
You need to select the form like
var sub = document.querySelector("#register");//If register is your form id Not input[type='submit']

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.

How to validate textarea and checkboxes which are generated dynamically

This one seems really common question in StackOverflow. However, I am having difficulty in validating these textarea (Not to left blank) and checkboxes(At least one should be checked). I tried several validation Javascripts and frameworks but in vain.
I have textarea named "case_title0[]" whose will increase the number "0" to "1","2" and so on when user clicks "Add More" button. I want to validate at the point when user clicks the "Add More" button.
Secondly, I want the checkbox (name="editioncheck'+caseNum+'[]") which is dynamic as well to restrict user to leave it blank. The checkbox looks like "editioncheck0[]", "editioncheck1[]" and so on. It needs to be checked at least once to proceed to next "Add More" button. Until then "Add More" button should remain inactive.
So, I want these two type of validation in my form ie. textarea and checkbox.
Which is the simplest framework or custom code to use here?
I don't want fancy display as just alert() box should work in this regard.
Add common class to all textareas and common class to all checkboxes and perform validation.
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<input type="checkbox" class="c">
function validate() {
var err = false;
$('.t').each(function(){
if($(this).text().length < 1) {
err = true;
return false;
}
});
if(!err) {
/* code to validate checkboxes like above */
}
return !err;
}
Finally, I have figured out the solution and I am going to post it here. As there is no exactly similar solution to my problem I had to code from scratch. While doing so lot of online resources helped me a lot.
To validate textarea on the fly (dynamic generate of text area when user clicks "Add More" button), here is solution I applied:
var csn='case_title'+caseno; //here "caseno" is incremental number to uniquely identify elements
var csum='case_summary'+caseno;
var caset=document.getElementById(csn).value;
var casesum=document.getElementById(csum).value;
if (caset == null || caset == "") {
alert("Executive Summary must be filled out");
caseNum --;
return false;
}
if (casesum == null || casesum == "") {
alert("Summaries with links must be filled out");
caseNum --;
return false;
Next, to validate the checkboxes I did as follows:
var edval='editioncheck'+caseno;
var checkBoxes=document.getElementsByClassName(edval);
var isChecked = false;
for (var i = 0; i < checkBoxes.length; i++) {
if ( checkBoxes[i].checked ) {
isChecked = true;
};
};
if ( isChecked ) {
//alert( 'At least one checkbox checked!' );
} else {
alert( 'Select at least one edition!' );
caseNum --;
return false;
}
The solution seems similar to the concept of fr34k, so thanks a lot. However, I found this online here http://jsfiddle.net/qyE97/
So, every time user click "Add More" button this script is executed and validates for the textarea and checkboxes.

javascript form validation - reloading of page

I have a form with some fields on. I am still learning Javascript. When my is submitted it triggers my JS which checks if the fields was submitted and then displays the errors in a which is done through innerhtml. Problem is it only display's the div for a few seconds and then finishes reloading the page and the div is not displayed anymore.
function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
}
}
You need to add
e.preventDefault();
for avoiding the default behavior.
Hence, if validation fails, the form won't be submitted.
please check whether your using normal HTML input element or ASP.NET server element. If your using Server element like then page will send back to server(reloaded) when click on button. the details you gave above is not enough.
you need to prevent the default behaviour if validation fails
you most likely do the validation on submit sth like:
$('form').submit(function(e){
check = checkradio() // let your function return true or false
if(!check){
e.preventDefault(); // add this to not submit the form
}
});
so the form will not submit if the validation fails
your tweaked validate function could look like this :
function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
return false;
}else {
return true;
}
}

Categories

Resources