Why javascript IF/ELSE doesn't work properly? - javascript

I'm new to JavaScript and I want to make username validation on registration form. I don't know what's wrong on my code but I think I have a problem with "IF ELSE" statement.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var usernameLength = $("#username").length;
$("#username").focusout(function() {
checkUser();
});
function checkUser() {
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
});
I expected that when I input more than 5 char until 20 char, the usernameErrorMsg will disappear. The actual result, no matter how many characters that I have input, the error message keeps coming up.

usernameLength is being computed only once, before checkUser() ever runs. You should re-calculate its value inside the callback each time; otherwise, changes to that value will not be visible inside the callback.
Furthermore, if you want to check the length of the test in the input, you need to check $("#username").val().length, not $("#username").length:
function checkUser(){
var usernameLength = $("#username").val().length;
if (usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}

$("#username").length is not the length of the characters in the field. It's the amount of elements in the JQuery wrapped set returned from your query. Since only one element will have an id of username, the length is always 1 and your if condition will always be true.
What you'll have to do is get the length of the value in the field:
$("#username").val().length
You'll also want to move the line that gets the value into the focusout event handler so that you are always working with the most current data.
Lastly, it doesn't make much sense to have a function do nothing but call another function, so you can combine the checkUser function with the event callback and simplify the code.
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var username = $("#username"); // Find the element just once
$("#username").focusout(function() {
// Each time the user leaves the field, get the current
// amount of characters in the input field
var usernameLength = username.val().length;
// See the difference between the length of the JQuery query and
// the length of the value of the first element in the results?
console.log(username.length, usernameLength);
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your name: <input id="username">
<span id="usernameErrorMsg">ERROR</span>

You need to get the length of input everytime the function checks it.
Currently you calculate the length only once.
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
//calculate the length everytime in the function
var usernameLength = $("#username").val().length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}

try this
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
usernameLength = $("#username").length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
});

Related

How to check entered value is exist or not using Jquery or javascript

I have one textbox and one button and on button I have written below code. problem is suppose first I have entered in textbox 10 than its worked but when another time I enter 10 than also it prints value is not in array. so pls help me whats the issue...
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
var ids = [];
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
This line:
if($.inArray(code,ids) >= 0)
should be changed to:
if($.inArray(code,ids) != -1)
and put your ids var outside of click.
Try the snippet below.
var ids = [];
jQuery("button").on('click', function() {
var sel_fam_rel = jQuery("#my_textbox").val();
code = sel_fam_rel;
if ($.inArray(code, ids) != -1) {
alert("Value is in array");
} else {
alert("Value is not in array");
ids.push(code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='my_textbox'>
<button>check</button>
Create your array var ids=[];global outside button event, as whenever you click button it is creating new empty array. It will fix your problem.
A few changes are needed:
var ids = []; // `ids` needs to be in the global scope to work as you want it,
// or you could use a different method like localstorage
jQuery(document).ready(function()
{
jQuery("#mybutton").on('click',function () // use `on` not `live` which is deprecated
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) != -1) // inArray() returns -1 if the value is not in the array, you can use it the way you have it, IMO (purely subjective), using `!=-1` is preferable as it's more clear what the code in intend to do
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_textbox" value="10"/><br>
<input type="button" id="mybutton" value="Click me"/>
use below code . take your ids out side of click event . as per your code each time when you click button ids reset .
var ids = []; // declare as global variable
jQuery(document).ready(function()
{
jQuery("#mybutton").live('click',function ()
{
var sel_fam_rel=jQuery("#my_textbox").val();
code =sel_fam_rel;
if($.inArray(code,ids) >= 0)
{
alert("Value is in array");
}
else
{
alert("Value is not in array");
ids.push(code);
}
});
});
I made a fiddle to your problem, Use indexOf
http://jsfiddle.net/go8o34fq/
jQuery-
var array=["A","B","C","D"];
$('button').click(function(){
var code=$('input').val();
if(array.indexOf(code)==-1)
{
array.push(code);
console.log("if "+array)
}
else
{
console.log("else "+array)
}
});
Just a bit requirement if your need is case-sensitive then use- code.toUpperCase()

jquery validation loop producing false positives

$(document).ready( function()
{
// hides the story and error text when the page loads
$('.errorText').hide();
$("#story").hide();
// global variables for the blanks and the textarea forms
var input = $("form").children();
var storyBlank = $('#story').children();
// Main Event on Click
$('button.submit').on( "click", function (event)
{
// if the form is not validated, highlights errors and prevents the submit from going through
if(!validate())
{
event.preventDefault();
}
// if the form is validated, fills the blanks in the story and displays it
else
{
fillInTheBlanks();
}
});
// Checks to see if there are any empty fields and highlights them if they are empty
function validate()
{
console.log('validate() initiated')
var success = false;
errcnt = 0;
cnt = 0;
while (cnt < 9)
{
if (input.eq(cnt).val().length == 0)
{
errcnt++;
input.eq(cnt).removeClass("hide");
console.log('errorcount', errcnt, 'at input', cnt);
}
else if (input.eq(cnt).val().length !== 0 && !(input.eq(cnt)).hasClass("hide"))
{
input.eq(cnt).addClass("hide");
}
cnt++;
}
if (errcnt == 0)
{
success = true;
}
return success;
}
// Fills in the blanks of the story
function fillInTheBlanks()
{
console.log('fillInTheBlanks() executed');
var blankCount = 0;
while (blankCount < 9)
{
storyBlank.eq(blankCount).empty().append(input.eq(blankCount).val());
blankCount++;
}
$("#story").show();
}
});
I am trying to make a mad libs style page with 9 textboxes for input. I am running into two problems.
First, when I click submit with all textboxes empty, only the the first four show an error (this is done in css, I have two classes on all the textboxes "error hide", I remove the class hide in my loop to show the error).
The second problem I'm having is if I click submit with text in all the textboxes, my validate functions errorcount goes up to 4 errors at every other textbox. I've even tried '$('input').eq(0).val().length == 0' for every textbox in the index and it's returning false every time. I don't understand how it's getting into that if then statement if it doesn't satisfy the argument.
i don't understand your problem, but if is validation on inputs empty... using
http://parsleyjs.org/

Class not removing on click

$(document).ready(function (){
var postcode = $('#postcode-form').val();
function errors(){
if(postcode == ""){
$('#postcode-form').addClass("form-error");
}else{
$('#postcode-form').removeClass("form-error");
}
}
$('#submit-form').click(errors);
});
The class adds when the form is empty but doesn't remove when I enter details in the form. I don't understand why?
Move the postcode chunk of code within your function. Otherwise it gets the value only once when the page loads. By placing it within the function, it'll check the value on each click.
function errors() {
var postcode = $('#postcode-form').val();
if (postcode == "") {
$('#postcode-form').addClass("form-error");
} else {
$('#postcode-form').removeClass("form-error");
}
}
So now you know why it isn't working. I would take advantage of the blunder though, and refactor to cache the selector!
$(document).ready(function (){
var $postcode = $('#postcode-form');
function errors(){
if($postcode.val() == ""){
$postcode.addClass("form-error");
}else{
$postcode.removeClass("form-error");
}
}
$('#submit-form').click(errors);
});

Validate multiple textboxes

I have this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});

JavaScript greater than not working

I have a JavaScript snippet:
function verifyFrnds(){
var boxes=$(".matchFrnds:checked").length;
//alert(boxes); its value is 50 when you do alert
var call=1;
$(".matchFrnds").each(function(index){
if($(this).is(':checked')){
call++;
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
//alert(call); value is 1
// 1 >=50 should be false but all the time the condition gets true
if(call >= boxes)
{
window.location.reload();
}
}
});
}
The question is self explanatory. The conditions gets true even when it is not. Not sure if it is due to that it is not treating them as numbers and strings may be, but all the time the condition gets true.
I'm missing some context but try this:
function verifyFrnds() {
var boxes = $(".matchFrnds:checked").length;
$(".matchFrnds:checked").each(function(index) {
var sendData= $(this).val();
$.post('SOME PHP Page',{sendData:sendData},function(data){
//window.location.reload();
});
if(index >= boxes-1) {
window.location.reload();
return false;
}
});
}
use below code
if(parseInt(call) >= parseInt(boxes))
{
window.location.reload();
}
Doesn't window.location.reload() from your post callback resets your checkboxes thus none being checked ?
1 will always be greater than 0
Of course that this depends on how the form is initialized in HTML, but we don't know this from your example.
Maybe if you present to us a more detailed explanation of what you have and what you want to do, we can present you a better solution.

Categories