Form checking does not work as expected

It seems you can fade the placeholder text in and out of you do something like this:

input.form-control::placeholder{
  color:red;font-weight:bold;text-indent:100px;transition:all 1s ease;
} 
input.form-control:focus::placeholder{color:rgba(255,255,255,0)}

(Not tested in anything else but chrome)

At present the test works using :focus so as I mentioned before change your js to add and remove classes and then you can tie that style change in to using a class instead of focus…

If I get a chance later I’ll do a demo.

Here it is rough and ready as it is but you should get the picture :slight_smile:

The styling is done through css and the js just adds/removes a class as required.

I also forgot to mention that you can only move the ::placeholder in Chrome. The other browsers will have text-align:center instead.

thank you for help and a bit late : marry christmass.
the code is lovely.
unfortunately I have another problem, trying to control input fields with if condition + console log but focusin and out looks different from on… .
please help me, thank you, frank

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
   height:60px;
  }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
   
  $(".box input").focusin(function(){
    $(this).css("background-color", "pink");
  });
  $(".box input").focusout(function(){
    $(this).css("background-color", "#FFFFFF");
  });
});

</script>
</head>

<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
   
  $(".box input").focusin(function(){
  console.log('changed');
  if ((".box" this).val() == "") {
    $(this).css("background-color", "pink");
  });
  } else {
    $(this).css("background-color", "lightgreen");
  }
  $(".box input").focusout(function(){
    $(this).css("background-color", "#FFFFFF");
  });
});

</script>
</head>
<body>

<div class="box" style="border: 1px solid black;padding:10px;">
  First name: <input type="text"><br>
 
</div>
<div class="inputstatus">
				<span class="glyphicon  glyphicon-star"></span>
				<span class="fielderror">Your first name</span>
		  </div>
          
<div class="box" style="border: 1px solid black;padding:10px;">
  Last name: <input type="text">
  
</div>
<div class="inputstatus">
				<span class="glyphicon  glyphicon-star"></span>
				<span class="fielderror">Your last name</span>
		  </div>
          
<p>Click an input field to get focus. Click outside an input field to lose focus.</p>

</body>
</html>

When I load your test page, the browser console does report:

Uncaught SyntaxError: Unexpected token 'this'

The first line in this code excerpt is the cause of the trouble:

  if ((".box" this).val() == "") {
    $(this).css("background-color", "pink");
  });
  } else {
    $(this).css("background-color", "lightgreen");
  }

I suspect that you’re wanting something like $(this).val() instead, and the }); is invalid too where it is, and and must be moved to after the end of the if/else statement.

    if ($(this).val() == "") {
      $(this).css("background-color", "pink");
    } else {
      $(this).css("background-color", "lightgreen");
    }
  });
1 Like

Hi Paul
thank you for help. I have a problem that blocks me literally. I have this code where I try to do background color switch with console.log(‘changed’).
unfortunately if condition wasn’t working properly in focusin/focusout.
when you click on the input field doesn’t react right away.
also as I type in the input field (modifying) field color changes from lightgreen to pink, that is not good.
thank you

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  
  <script>
$(document).ready(function(){
   
   $(".form-control").on( "blur input", function( ){
   console.log('changed');
   var vr = $(this).attr('name');
   var inp = $(this).val().trim();
    if ( inp === "" ){
      
	  alert(vr + ' can not be left blank');
	  $(this).next().html(vr + " is empty ");
		   $("input").focusin(function(){
		   $(this).css({"background-color": "pink",
					 "border":"1px solid green"
					});
			  });
		   $("input").focusout(function(){
			$(this).css({"background-color": "#FFFFFF",
						"border":"1px solid gray"
						});
		   });
      event.preventDefault();
     } 
	else {
	    $("input").focusin(function(){
		   $(this).css({"background-color": "lightgreen",
					 "border":"1px solid green"
					});
			  });
	 // $(this).next().html(vr + " is ok ");
   }
  });
  
  $(".btn1").click(function(){
  $( ".form-control" ).each(function() {
  var vr = $(this).attr('name');
    if ($('input').val().trim() != ""){
      
	  alert(vr + ' can not be left blank');
	  $(this).next().html(vr + " is empty ");
      event.preventDefault();
   } else {
	  
	  $(this).next().html(vr + " is ok ");
   }
  });
  });
});
</script>
</head>
<body>

<div class="container">
  <h2>Vertical (basic) form</h2>
  <form >
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
	  <span>email</span>
    </div>
    <div class="form-group">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
	  <span>password</span>
    </div>
    <div class="checkbox">
      <label><input type="checkbox" name="remember"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-default btn1">Submit</button>
  </form>
</div>

</body>
</html>

No it won’t, because you are using the blur end the input events. When you click in a field that is the focus event, I suspect that you want to use focus instead, if you want color to change when someone clicks on the input field.

Yes, that is right, so that means I have to change blur to focusin, focusout, If I am right, just console.log() won’t work I guess. can You give me idea how to solve this problem?thank you, frank

Why are you wanting to log “changed” when someone clicks on an input field. That doesn’t make sense because nothing has changed, yet.

Hi Paul
Thank you for answer. I think there are two things: first is clicking on input. When empty, the background color should be pink, if not lightgreen. second, as I start typing it should change bacground also and any error message. thank you, frank,

I recommend that instead of doing everything from the one event handler, that you use a range of different event handlers so that you can more easily deal with what needs to be done.

Ho Paul
thank you for answer. I am not sure if I am right but reading your answer, I’ve got the following idea, please have a look, thank you, frank

<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//  $("p").on("click", function(){
//    alert("The paragraph was clicked.");
     $(".form-control").on( "focusin .box input", function( ){
   console.log('changed');
   var vr = $(this).attr('name');
   var inp =$(this).val().trim()
    if ( inp === "" ){
      
    //  alert(vr + ' can not be left blank');
      $(this).next().html(vr + " is empty ");
	  $(this).css("background-color", "pink");
      event.preventDefault();
     }
    else {
      $(this).css("background-color", "lightgreen");
      $(this).next().html(vr + " is ok ");
   }
    
  });
   $(".form-control").on( "focusout .box input", function( ){
   console.log('changed');
   var vr = $(this).attr('name');
   var inp =$(this).val().trim()
    if ( inp === "" ){
      
      alert(vr + ' can not be left blank');
      $(this).next().html(vr + " is empty ");
	 $(this).css("background-color", "white");
      
    
      event.preventDefault();
     }
    else {
      $(this).css("background-color", "lightgreen");
      $(this).next().html(vr + " is ok ");
   }
    
  });
});
</script>
</head>
<body>

<p>Click this paragraph.</p>
<h2>Vertical (basic) form</h2>
  <form >
    <div class="form-group">
	<div class="box">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
      <span>email</span>
    </div>
	</div>
    <div class="form-group">
	<div class="box">
      <label for="pwd">Password:</label>
      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
      <span>password</span>
    </div>
	</div>
    <div class="checkbox">
      <label><input type="checkbox" name="remember"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-default btn1">Submit</button>
  </form>
</body>
</html>

Okay, let’s try and improve this code.

First, jquery is only needed once. Remove the duplicate:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  
<!--script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>-->

Then, move the scripts down to the end of the body.

<head>
    ...
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script>
    ...
    </script>-->
</head>
<body>
    ...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
    ...
    </script>
</body>

Because the scripts are now properly at the end of the body, there’s no need now for the document ready part.

     // $(document).ready(function(){
            $(".form-control").on( "focusin .box input", function( ){
                ...
            });
            $(".form-control").on( "focusout .box input", function( ){
                ...
            });
     // });

Now that the code is in a tidier state, we can look through what you want and put together a todo list.

  • required caused problems
  • wants placeholders to fade out
  • when empty field, the background color should be pink, if not lightgreen
  • as I start typing it should change bacground

As the existing code is confusing and causing troubles, this is now when we remove all of the scripting code and start over.

     // $(".form-control").on( "focusin .box input", function( ){
     //     console.log('changed');
     //     ...
     // });
     // $(".form-control").on( "focusout .box input", function( ){
     //     console.log('changed');
     //     ...
     // });

color the fields

You were wanting the field to be pink when not filled, and otherwise lightgreen.

Because you’re using bootstrap, I can’t use the input selector to color the fields:

input { /* doesn't work with bootstrap */
    background: pink;
}

Instead of that, the bootstrap form-control selector can be updated.

form-control {
    background: pink;
}

And all of the form fields are colored pink.

valid fields

How do we color them green when things are okay? We can add green to the :valid selector

        .form-control:valid {
            background-color: lightgreen;
        }

All the fields go green, because they are currently optional and don’t need to be entered. Let’s fix that.

required fields

We can add required to the fields that must be entered. Let’s add required to the email field:

<input type="email" required class="form-control" id="email" placeholder="Enter email" name="email">

And also add required to the password field:

<input type="password" required class="form-control" id="pwd" placeholder="Enter password" name="pwd">

And now, the form starts with the fields pink, and stays pink while the field is not valid.
When a valid email address is entered, the field goes green. Nice.

  • required caused problems
  • wants placeholders to fade out
  • when empty field, the background color should be pink, if not lightgreen
  • as I start typing it should change bacground

fading out placeholders

The fading out of placeholders is achieved with the following CSS code:

        input.form-control::placeholder {
            color: red;
            font-weight: bold;
            text-indent: 100px;
            transition: all 1s ease;
        } 
        input.form-control:focus::placeholder {
            color: rgba(255,255,255,0);
        }

Remove scripting code

As all of this was dealt with without needing any scripting, the jquery library and the bootstrap javascript library and the scripting code, can all be removed.

<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script>
        // $(".form-control").on( "focusin .box input", function( ){
        // ...
        // });
    </script> -->

The code

Here is the bootstrap form page with much better and more reliable presentation and form validation.

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <style>
        .form-control {
            background-color: pink;
        }
        .form-control:valid {
            background-color: lightgreen;
        }
        input.form-control::placeholder {
            color: red;
            font-weight: bold;
            text-indent: 100px;
            transition: all 1s ease;
        } 
        input.form-control:focus::placeholder {
            color: rgba(255,255,255,0);
        }
    </style>
</head>
<body>
    <p>Click this paragraph.</p>
    <h2>Vertical (basic) form</h2>
    <form>
        <div class="form-group">
            <div class="box">
                <label for="email">Email:</label>
                <input type="email" class="form-control" id="email" placeholder="Enter email" name="email" required>
            </div>
        </div>
        <div class="form-group">
            <div class="box">
                <label for="pwd">Password:</label>
                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" required>
            </div>
        </div>
        <div class="checkbox">
            <label><input type="checkbox" name="remember"> Remember me</label>
        </div>
        <button type="submit" class="btn btn-default btn1">Submit</button>
    </form>
</body>
</html>

summary

We have now taken care of the whole todo list, with no JavaScript being needed at all.

  • required caused problems
  • wants placeholders to fade out
  • when empty field, the background color should be pink, if not lightgreen
  • as I start typing it should change bacground

When you attempt to submit an invalid form, you are given large error messages telling you what needs to be done. Those error messages also appear when you hover on invalid fields.

Is there anything more that needs to be done?

3 Likes

Thank you for help.
The pink color I would use when clicking on the input is empty. as I click out of the input it should change to whiye; if I type something , then change to light green continuously, for this reason did I use on)() + focusin and out without required.
also I post my floatig label experiment

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script>
  	$(document).ready(function(){
    
	  $("input").focusin(function(){
			//$(this).css("position","relative");
			$(this).css({"background-color": "lightgreen",
                         "border":"1px solid green",
                         "color": "red"
            });
            $(this).nextAll(".float").css({"color":"green",
            									"bottom":"35px",
												"left":"2px"
												});
			$(this).nextAll(".email_placehold").css("color","lightgreen"
            									);	
												
			$(this).nextAll(".pw_placehold").css("color","lightgreen"
            									);								
           
			//$(this).addClass(".float");
		
	  }); 
	  $("input").focusout(function(){
			//$(".pwbb").css("position","relative");
			$(this).css({"background-color": "#FFFFFF",
					"border":"1px solid gray",
                    "color": "gray"
					});
			$(this).nextAll(".float").css({"color":"gray",
            									"bottom":"4px",
												"left":"35px"
												});
												
			$(this).nextAll(".email_placehold").css("color","green"
            									);									
		    $(this).nextAll(".pw_placehold").css("color","green"
            									);

 }); 
 }); 
  </script>
  <style>
  .box{
  	position:relative;
    
    }
  
  .float{
  	 position:absolute;
     bottom:3px;
     left:32px;
	 color:gray;
   }
   .glyph{
     position:absolute;
   	 top:13px;
	 left:10px;
    }
	.email_placehold{
     position:absolute;
   	 top:11px;
	 left:82px;
    }
	.pw_placehold{
     position:absolute;
   	 top:11px;
	 left:112px;
    }
  </style>
</head>
<body>

<div class="container">
  <h2>Vertical (basic) form</h2>
  <form>
    <div class="form-group">
       <div class="box">
         <input type="email" class="form-control" id="email" placeholder="" name="email">
         <label class="glyphicon glyphicon-envelope glyph" for="email">
		 
		 </label>
		 <b class="email_placehold">Like John.Doe@email.com</b>
		  <span class="float">Email :</span>
	   </div>
	   <span></span>
    </div>
    <div class="form-group">
       <div class="box">
          <input type="password" class="form-control" id="pwd" placeholder="" name="pwd">
	      <label class="glyphicon glyphicon-lock glyph" for="pwd">
		  </label>
		  <b class="pw_placehold">Like Password123</b>
		  </label>
		  <span class="float">Password :</span>
       </div>
	   <span></span>
	</div>
    <div class="checkbox">
      <label><input type="checkbox" name="remember"> Remember me</label>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

</body>
</html>

That couldn’t be easier, and doesn’t require JavaScript at all.

You just need to add :focus to the CSS style from my previous post.

      /*.form-control { */
        .form-control:focus {
            background-color: pink;
        }

Here’s the full code:

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <style>
        .form-control:focus {
            background-color: pink;
        }
        .form-control:valid {
            background-color: lightgreen;
        }
        .form-control::placeholder {
            font-weight: bold;
            transition: all 1s ease;
        } 
        .form-control:focus::placeholder {
            color: rgba(255,255,255,0);
        }
        .form-control {
            padding-left: 6em;
        }
        .box{
            position:relative;
        }
        .glyph{
            position:absolute;
            top:8px;
            left:10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Vertical (basic) form</h2>
        <form>
            <div class="form-group">
                <div class="box">
                    <input type="email" required class="form-control" id="email" placeholder="Like John.Doe@email.com" name="email">
                    <label class="glyphicon glyphicon-envelope glyph" for="email"> Email:</label>
                </div>
                <span></span>
            </div>
            <div class="form-group">
                <div class="box">
                    <input type="password" required class="form-control" id="pwd" placeholder="Like Password123" name="pwd">
                    <label class="glyphicon glyphicon-lock glyph" for="pwd"> Password:</label>
                </label>
            </div>
            <div class="checkbox">
                <label><input type="checkbox" name="remember"> Remember me</label>
            </div>
            <button type="submit" class="btn btn-default btn1">Submit</button>
        </form>
    </div>
</body>
</html>

In summary, it’s bad and tends to be a trap to use JavaScript, when other things like HTML and CSS do the job just as well if not better.

1 Like

Thank you for answer and happy new year from Hungary, Friday I’ll go back to London UK.
I agree with you but this is a programming challenge, also I hope it won’t collide with php.

Yes, and HTML and CSS are also programming.

If you are doing this as a class project, then you should share with us details of what your teacher/tutor requires.

I’ve taken a 10week jquery course in London Hammersmith Macbeth centre and as a practice I try to build a custom system with validation. As you can see, elements of it works but assembling them into one system is very difficult even harder then pascal.
I would like to post the latest development if you agree with. thank you, frank.

There are several reasons why JavaScript is not suitable for what you’re doing there, but the main one is that it really slows down loading of the page when jquery and bootstrap scripts have to be loaded, resulting in a worse user experience.

Are you wanting to find out how normal techniques are done in a less effective way using JavaScript instead? Because that’s the impression that we’re getting from you right now.

If not that, then what?

one thing is the normal thing the other is having some programming experience in pascal and at the moment learning c++, influenced from programming, trying to build the mentioned thing but things happens that I do not understand, please hep me, thank you, frank