Bootstrap error alert using jQuery - javascript

I'm trying to display error alert messages using bootstrap alerts. If a user submits the form with some fields empty, an error should be displayed. However when i click submit nothing is displayed.
JS
<script type="text/javascript">
$(document).ready(function () {
$('form[name="register"]').on("submit", function (e) {
var email = $(this).find('input[name="email"]');
if ($.trim(email.val()) === "") {
e.preventDefault();
$("#errorAlert").slideDown(400);
} else {
$("#errorAlert").slideUp(400, function () {
email.val("");
});
}
});
$(".alert").find(".close").on("click", function (e) {
e.stopPropagation();
e.preventDefault();
$(this).closest(".alert").slideUp(400);
});
});
</script>
HTML
<div class="alert hide" id="errorAlert">
<a class="close">×</a>
Oops!!. You may have left some fields empty. Please fill them out.
</div>
<form name="register" action="" method="post">
<input type="text" name="email" />
<input type="submit" class="btn" value="Submit" />
</form>
When i remove the "hide" class from the div above, the alert message comes up even before the form is submitted. If i then close the alert and submit the form, the alert isn't displayed. How do i get it working. Thanks in advance

on your $("#errorAlert").slideDown(400), add .removeClass('hide')
that would be $("#errorAlert").hide().slideDown(400).removeClass('hide').
I'm suspecting hide class has display:none!important. so we have to remove the class.
DEMO fiddle

Demo
jquery
$(document).ready(function () {
// Run this code only when the DOM (all elements) are ready
$('form[name="register"]').on("submit", function (e) {
// Find all <form>s with the name "register", and bind a "submit" event handler
// Find the <input /> element with the name "username"
var email = $(this).find('input[name="email"]');
if ($.trim(email.val()) === "") {
// If its value is empty
e.preventDefault(); // Stop the form from submitting
$("#errorAlert").slideDown(400); // Show the Alert
} else {
e.preventDefault(); // Not needed, just for demonstration
$("#errorAlert").slideUp(400, function () { // Hide the Alert (if visible)
alert("Would be submitting form"); // Not needed, just for demonstration
username.val(""); // Not needed, just for demonstration
});
}
});
$(".alert").find(".close").on("click", function (e) {
// Find all elements with the "alert" class, get all descendant elements with the class "close", and bind a "click" event handler
e.stopPropagation(); // Don't allow the click to bubble up the DOM
e.preventDefault(); // Don't let any default functionality occur (in case it's a link)
$(this).closest(".alert").slideUp(400); // Hide this specific Alert
});
});

The problem's pretty simple. .hide is not a good idea to use here because it contains display: none with !important following it, so even when you are trying to display the alert, this property overrides it.
You could create a simple css:
.hid{
display:none;
}
Add the hid as class to the alert box instead of hide.
DEMO

You could simply delete the hide class and add style="display:none;" to the $('#errorAlert') element. This way, the element will not appear on page load, and jQuery will manipulate the display property when using slide* functions. (it would never delete/add Bootstrap's hide class.)
See fiddle: http://jsfiddle.net/X2B9h/

UPDATED: http://jsfiddle.net/crw4K/
EDIT: Changing my answer because I haven't had my coffee yet.
Okay, so my changes to your code:
I removed the class 'hide' from the alert div, and added an inline style tag with 'display:none;'
Also, I removed the initial
$(".alert").find(".close")...
and changed it to just
$(".close").on("click"...
EDIT: I think I have found your problem. The .hide class in bootstrap is:
display:none !important;
which means it takes top priority over every other css for the element. Meaning that when you do slide down, the display:none !important is still taking priority.
You could either remove the class entirely, and add your own inline style tag (as I have in my answer) or you could remove the class with jquery.

Related

How can ı see text after submit form

I have a form and validation. I need form is full and after submitting just Successfull text. ı wrote that code but text is coming even if the form is not full
$(function() {
$('form').on("submit",function(e) {
$("#_supportFormContainer").removeClass("col");
$("#_supportFormContainer").css("display", "none");
setTimeout(function(){
$('#contact-text-div').show();// or fade, css display however you'd like.
}, 3000);
});});
In order to hide a form when it is submitted I would append a listener to the submit event of the form
$("form").submit(function(event) {
$(this).hide()
});
Then, in order to show the div, I would also add $("#myElem").show();.
If you also want to block the page reload you can add event.preventDefault(), in order to avoid the use of onsubmit="return false;" on the form itself.
But maybe you also want to hide $("#myElem") on document ready, so you can add $("#myElem").hide()
Putting all together, the script become
$(function() {
$("#myElem").hide()
$("form").submit(function(event) {
event.preventDefault()
$(this).hide();
$("#myElem").show();
});
});

JQuery Validate - Add/remove error css class in the form

I want to add/remove the error css class in the form.
$("#my-form").validate({
invalidHandler: function (event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
},
});
Problem with this approach:
When I use $("#my-form").validate().form() to validate the form, it will automatically add/remove the error css-class to each of the controls such as an input. By adding invalidHandler this additionally will add/remove the error css-class of the whole form.
Once I do validator.resetForm() to clear the messages, this will reset the css-class from the children controls but not from the form. I wish it automatically removes the css-class from the form by using a binding or any other sort of handler that trigger this action (removing the css-class from the form).
How I can fix this problem?
Source: http://jqueryvalidation.org/validate/
Update
Here a silly example: http://jsfiddle.net/F2Re4/ and I manually remove the class (in this example, I called the class: 'error-form')
Looking at the markup of your jsFiddle,
<input type="button" onclick="validate()" value="Validate"></input>
<input type="button" onclick="resetForm()" value="Reset Form"></input>
1) input elements do not have a closing tag. They may or may not need to be "self-closing" depending on your doctype, but there is never any such thing as an </input> tag.
2) Inline JavaScript is ugly and unnecessary when you use jQuery. onclick handlers can easily be removed and replaced with jQuery .on('click')...
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm();
});
3) You do not need a validate function attached to your "validate" button. Simply change the button into a type="submit" and it will be validated automatically. Otherwise, you would need another .on('click') handler and a .valid() within to trigger a validation test.
<input type="submit" id="validate" value="Validate" />
<input type="button" id="reset" value="Reset Form" />
Quote OP:
... validator.resetForm() to clear the messages, but this invalidHandler is never called and the 'error' css class still there in the form.
As per documenation, invalidHandler is only called when the form is invalid. If you reset the form, the form is no longer invalid. Therefore, the logic used within your invalidHandler is flawed.
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("form-error");
} else {
// this will never be called because invalidHandler
// is never called when there are no form errors
//$(this).removeClass("form-error");
}
There is nothing in this plugin that will automatically add/remove the class of the <form> element itself. The plugin only automatically adds/removes classes from the various data input elements. Therefore, if you manually add a class to the <form> element, then you're going to have to manually remove it when you reset the form.
$(document).ready(function () {
$("#myForm").validate({
// your rules & options
});
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm(); // reset validation on form
form.removeClass("form-error"); // remove error class from form
});
});
DEMO: http://jsfiddle.net/F2Re4/11/
Use .valid() to test the form. See the click function for valid()
validate = function(){
$("#myForm").valid();
};
resetForm = function(){
var form = $("#myForm").validate();
form.resetForm();
};
DEMO: http://jsfiddle.net/tive/U2XKx/
Additionally use reset() as seen on w3schools to clear the text value.

Hide Alert until parsley makes an error

I have made a form using Parsley validation and put the alerts inside an alert bar using bootstrap.
Now I want the alert bar to be hidden until parsley triggers an error. I don't know enough about parsley to be able to do this. How could we do this?
You can find all my code and an example at: http://jsfiddle.net/7m7DR/2/ (although the validation doesn't seem to be working in the jsfiddle website) :/ ??
the alert bar looks like this:
<div class="alert">
<ul id="alert" style="list-style-type:none;">
<li style="list-style-type:none;"></li>
</ul>
</div>
You have to declare your parsley form in JS and override the default onFormSubmit Listener. Also hide your alert div with a css class and then remove the class when you want to display it.
$(function () {
$('#someForm').parsley({
listeners : {
onFormSubmit : function (isFormValid, event) {
if(!isFormValid) {
//display your error div
}
}
}
});
});
If you want to add more specific messages to your alert take a look at the onFieldValidate and onFieldError listeners http://parsleyjs.org/documentation.html#javascript

JQuery click of input button not firing

I've looked on the forum and my question is a duplicate of Button click event not firing in jQuery, except my code already matches the given answer.
I've stripped this down for you guys anyway, and can confirm that links with a class of disabled do not fire, so this proves the document ready and Jquery library are correct.
Javascript
$(document).ready(function () {
// Prevents links from firing
$('a.disabled').click(function (e) {
e.preventDefault();
});
// Handles search
$("#btnTreeSearch").click(function () {
alert("click search fool!");
});
});
Html
<input type="submit" value="btnTreeSearch" />
Any clues?
You need to assign id to input to use id selector
Live Demo
Html
<input type="submit" id="btnTreeSearch" value="btnTreeSearch" />
Javascript
$("#btnTreeSearch").click(function () {
alert("click search!");
});
Change value="btnTreeSearch" to id="btnTreeSearch".

remove class with formSubmit

my error message below, with a highlighted field is working perfectly. Except now the powers that be want a different functionality.
Currently the error messaging highlights the field with a red border, and on focus the border is removed. However, now the powers that be want the red highlighting to persist until the user hits submit onclick="return formSubmit()"
I've tried using a .submit function (removing the unbind and remove focus from the .focus function, but the red highlighting persists regardless.
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$(this).removeClass("CO_form_alert")
.parent().removeClass("alertRed"); // undo changes
$('.errorPopup').hide(); // hide error popup
});
}
Not sure I understand you. If not please tell me, but can't you just do:
$('.theform').submit(function() {
$('input', this).removeClass('CO_form_alert').parent().removeClass('alertRed');
$('.errorPopup').hide();
return false;
});
Why do you need to unbind?
I was so narrow minded in my looking for a solution above - trying to tie the removeClass with the form submit (which had to many actions tied into it and would have been overly complicated).
Instead, I just did a remove class at the beginning of the error checking:
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");

Categories