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
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
I'm trying to build a small login system using jquery (since it is for testing purposes only and the user and password won't change) So i made a form and when you click the button i test whether the details are correct. if so you will get send to the next page. If not i give an alert.
It's working but i have something weird. The first time you visit the site and fill in the details it does nothing. The second time (after submitting) it works like it should.
Does someone know why?
Here is the code:
function controllogin() {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username=="leerkrachten" && password=="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username=="leerling" && password=="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
};
function goToUrl() {
alert("zoeken naar pagina");
window.location = 'leerkrachten/vakken.html';
};
Instead of onclick="controllogin();" try something like this:
$('document').ready(function() {
$('#submit').click(function(event) {
event.preventDefault();
var username = $("#gebruikersnaam").val()
var password = $("#wachtwoord").val()
if (username==="leerkrachten" && password==="leerkrachten") {
alert("welkom leerkrachten");
goToUrl();
}
else if (username==="leerling" && password==="leerling") {
alert("welkom leerling");
}
else {
alert("verkeerde gegevens ingevuld");
}
});
});
Also use === instead of == as operators to compare the strings, it prevents you from some weird results when comparing different types. Maybe that's why it doesn't work the first time, but does the second time. Otherwise I don't know why this happens.
But actually I'd have to say: NEVER do client-side login validation and NEVER do login validation with an unencrypted password (not even server-side)!
Place holder is not working in IE-9,so I used the below code for place holder.
jQuery(function () {
debugger;
jQuery.support.placeholder = false;
test = document.createElement('input');
if ('placeholder' in test) jQuery.support.placeholder = true;
});
// This adds placeholder support to browsers that wouldn't otherwise support it.
$(function () {
if (!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form:eq(0)').submit(function () {
$(':text.hasPlaceholder').val('');
});
}
});
When I am taking the value of test,it shows null.How can I get the details of all input tag?
I think this will help you
if ($.browser.msie) {
$("input").each(function () {
if (IsNull($(this).val()) && $(this).attr("placeholder") != "") {
$(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
$(this).keypress(function () {
if ($(this).hasClass('hasPlaceHolder')) $(this).val("").removeClass('hasPlaceHolder');
});
$(this).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder")).addClass('hasPlaceHolder');
});
}
});
}
I'm on my mobile so this is hard but really you need to do
JQuery.support.placeholder = typeof 'placeholder' in test !== 'undefined'
Because null means there isn't any placeholder value, but there is placeholder support
From what I understand you're saying that the placeholder in test is returning null
I suggest you don't write this yourself and go for an off-the-shelf solution. There's more complexity here that you'd probably want to tackle yourself if all you want is provide support for older browsers.
For example, here's the shim I'm using (and that is recommended on http://html5please.com): https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js
Go ahead and read the code. These are some issues you need to have in mind when writing such shim:
detect the browser support,
keep track when the box contains the real input or not;
add a class to allow different text colour for the placeholder,
clear the placeholders before submitting the form,
clear the placeholders when reloading the page,
handle textarea,
handle input[type=password]
And that's probably not even all. (The library I've linked also hooks into jQuery in order to make .val() return '' when there's no real input in the box.
There's also another shim that uses a totally different approach: https://github.com/parndt/jquery-html5-placeholder-shim/blob/master/jquery.html5-placeholder-shim.js
This library doesn't touch the actual value of the input, but instead displays an element directly over it.
HTML:
<input type='text' id='your_field' value='Enter value'/>
jQuery:
$(document).ready(function(){
$("#your_field").on('focusout',function(){
if($("#your_field").val() == ''){
$("#your_field").val('Enter value');
}
});
$("#your_field").on('focus',function(){
if($("#your_field").val() == 'Enter value'){
$("#your_field").val('');
}
});
});
See DEMO
Also check when the form is posted because if the user submits the form without entering the field then Enter value will be posted as the value of the field.So do either validations in client side or check in the server side when submitting the form.
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.
I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.