I have JavaScript code that checks if all the fields in a form are filled, if not it pops up a bootstrap alert using jquery. This works fine with text inputs, but when checking selects, it always fires the error, even if an option is filled.
JavaScript Code:
$(document).ready(function () {
$('form[name="register"]').on("submit", function (e) {
var username = $(this).find('input[name="username"]');
var preferredClass = $(this).find('input[name="preferredClass"]');
if ($.trim(username.val()) === "" || ($.trim(preferredClass.val())) === "") {
e.preventDefault();
$("#formAlert").slideDown(400);
} else {
$("#formAlert").slideUp(400, function () {});
}
});
$(".alert").find(".close").on("click", function (e) {
e.stopPropagation();
e.preventDefault()
$(this).closest(".alert").slideUp(400);
});
});
The entire code and (Kind of) working example can be found in this JSFiddle.
you have wrong selector for your select
Replace this
var preferredClass = $(this).find('input[name="preferredClass"]');
With this:
var preferredClass = $(this).find('select[name="preferredClass"]');
Working Demo
Your select element selector is wrong.
Try to change the selector statement:
$(this).find('select[name="preferredClass"]');
Then your validation will be ok.
Hope this is helpful for you.
Related
I have a couple of forms on a site. On the first form I used the code below to add a border color if the input field is not blank and remove it if it is blank. This works just fine no issues. But I've found that when I try to use the same method on other forms, to do something else using the same logic, it does not work.
I have read through many forums and what I'm seeing is that the code is only read on page load. But I have forms that run the function after the page is far past loading. Can someone give some light to this? I'm really trying to understand the way this works fully.
Code that works on form:
var checkErrorIn;
jQuery(document).ready(function ($) {
checkErrorIn = setInterval(CheckErrorInput, 0);
});
function CheckErrorInput() {
if (jQuery('body').is('.page-id-6334')) {
// First Name, Last Name validation colors
var pasdFName = jQuery('#first_name').val();
var pasdLName = jQuery('#last_name').val();
if (pasdFName != '') {
jQuery('#first_name').addClass('formConfirm_cc');
} else {
jQuery('#first_name').removeClass('formConfirm_cc');
}
if (pasdLName != '') {
jQuery('#last_name').addClass('formConfirm_cc');
} else {
jQuery('#last_name').removeClass('formConfirm_cc');
}
if (pasdFName != '' & pasdLName == '') {
jQuery('#last_name').addClass('formError_cc');
} else {
jQuery('#last_name').removeClass('formError_cc');
}
if (pasdFName == '' & pasdLName != '') {
jQuery('#first_name').addClass('formError_cc');
} else {
jQuery('#first_name').removeClass('formError_cc');
}
}
}
Code that is not working:
if (jQuery('body').is('.woocommerce-page')) {
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
jQuery('.woo_login_form').on('input', function(){
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
if (checkActiveName =='') {
jQuery('.woo_login_form').removeClass('cdc_keep_active');
}
}
What I am trying to do is fix an issue with a form becoming hidden if not hovered over even when the input has characters. Based on my research I figured I'd do the .on to get the class added when the input got characters. That works but the removal of the characters isn't removing the class. The logic looks right to me. What am I missing?
Thank you in advance for your help and insight.
Update:
Ok so I ended up doing this:
jQuery('.woo_login_form').on('click', function () {
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
jQuery('.custom-login-box > a').on('click', function () {
jQuery('.woo_login_form').toggle();
});
For some reason my class would not add with any of the methods suggested individually so I combined the logic. The first part adds the class that makes the form visible but then the form won't close if clicked out of regardless of the 'removeClass'. So I added a toggle (thank you commenters) method to the "hovered link" to allow users to close the box if not needed.
Would still like to understand why the first method worked in one instance but not the other. Any and all insight appreciated. Thank you.
In your current code example you immediately check for the value of the username field.
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
The thing with this is that checkActiveName will never change, unless it is reassigned elsewhere in the code.
What you need to do is to check the current value after every input of the user. That means moving that line of reading the value of the input inside the input event listener.
if (jQuery('body').is('.woocommerce-page')) {
var $wooLoginForm = jQuery('.woo_login_form');
var $userName = jQuery('#username'); // This ID should only exist once, so no need for complex selectors.
$wooLoginForm.on('input', function() {
var checkActiveName = $userName.val();
if (checkActiveName =='') {
$wooLoginForm.removeClass('cdc_keep_active');
} else {
$wooLoginForm.addClass('cdc_keep_active');
}
});
}
On a sidenote: using setInterval to validate your form is a bad practice. This would basically run infinitely. It doesn't have to. You only have to check if a form is valid after the user enters a value.
Apply the same technique with the event listener like in your second code snippet.
var $document = jQuery(document);
$document.ready(function ($) {
/**
* It might even be better to listen for the input event on the form
* that has to be validated, but I didn't see it in your code.
* Right now it listens for input on the entire page.
*/
$document.on('input', CheckErrorInput);
});
I'm trying to modify some other code that I found on SO, but it's not working (I'm still learning JQ)
My code:
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
Basically (in case it's not clear) I want to fire that alert() as the user moves away from the textbox - only if the user entered something in the textbox.
Code seems to work, make sure the field is loaded before binding the event, preferably using $(document).ready()
$(document).ready(function(){
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
})
Here is the related fiddle
I'm wanting to ensure the "Email" radio button is checked on load rather than the phone.
For some reason the "Phone" radio button is checked onload yet both inputs are showing, I don't quite understand that.
DEMO HERE
Here is my jQuery
var ebuForm = {
init : function() {
ebuForm.showInput();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.prop('checked', true);
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val()=="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
}
};
$(function() {
ebuForm.init();
});
Working demo http://jsfiddle.net/2F88K/ or http://jsfiddle.net/775X2/
Order of the change event
triggering the cahnge event will do the trick.
If I may recommend: Try keeping your change event outside. see this radioInput.prop('checked', true).trigger("change");
The use of radioInput.prop('checked', true) is kind of interesting which I wont encourage. :) think that radio buttons are either / or i.e. one of the 2 will be selected at one point.
Hope rest fits your need. :)
Code
var ebuForm = {
init : function() {
ebuForm.showInput();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val() =="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
radioInput.prop('checked', true).trigger("change");
}
};
$(function() {
ebuForm.init();
});
First input[value='email'] is not such a good selector -- use #email instead. The reason the phone radio button is checked is because you are checking it with the code:
radioInput.prop('checked', true);
Your probably wanted to write:
emailRadio.prop('checked', true);
And remember you cannot check both phone and email! They both have the same name.
Try this
JS Fiddle
The key here is $('#email').prop('checked', true).trigger('change');
Many ways to do this...
Solution #1: (HTML)
You could use checked="checked"
JSFiddle Demo
Solution #2: (JQuery)
var email = $("#email");
email.prop('checked', true);
And to hide the phone input on page load, you can trigger the change event:
email.prop('checked', true).trigger('change');
JSFiddle Demo
I am having a very weird issue where the code of my working files doesn't work when the same code on my JS Fiddle works fine.
All I am doing is checking whether either username or password field is submitted blank.
For some reason, my working platform code doesn't pick up any input value.
I've gone through number of times, making sure that I am on same code environment
but everything is identical. I don't know where to take it from here.
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Is my if statement violating any rules that might result in inconsistency?
JS Fiddle
The problem is that your <form> element is submitting, thus reloading the page. I recommend modifying the form's submit event rather than giving the button a click event, as forms are usually but not necessarily triggered by clicking the button. Also, return false is not a good way of disabling behaviour.
Example:
(function($){
$('#form_1').submit(function (event) {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( username === '' || password === '' ) {
event.preventDefault();
$('.fa-user').removeClass('success').addClass('fail');
}
else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Here's the fiddle: http://jsfiddle.net/RyanJW/VqwNw/1/
check this
use return false to stop execution
(function($){
$('#signIn_1').click(function () {
var username = $('#username_1').val();
var password = $('#password_1').val();
if ( $.trim(username) === '' || $.trim(password) === '' ) {
$('.fa-user').removeClass('success').addClass('fail');
return false;
} else {
$('.fa-user').removeClass('fail').addClass('success');
}
});
})(jQuery);
Fiddle
Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);