You are here:

Javascript/Question about validation code java script


How can i put a check before  entering  data into next field if previous is empty. for example i have a login(with fields name and password).if i keep name empty and start putting password in password an alert will be show before entering data in password field( if name field is empty)
<head> <title> login </title>
<script language="javaScript">
which code will be written here
<body bgcolor="yellow">
<form name="frm1">
Enter Name    :<input type="text" name="txt1"><br>
Enter Password:<input type="password" name="pass1">

PLEASE help me about this

Hi Punjab,

Thanks for your question. Below is an updated version of your HTML with JavaScript added that shows an alert if the user attemps to enter anything in the passowrd text box, but the name text box is empty.

Here is the JS Fiddle link as well.

I hope this was helpful. Please feel free to follow-up if there are any other questions you may  have.

Best Wishes,

Kevin Chisholm

-----------UPDATED CODE------------------------

<!DOCTYPE html>
  <meta charset="utf-8">
     <form name="frm1">
     Enter Name :<input type="text" name="txt1" id="txt1"><br>
     Enter Password:<input type="password" name="pass1" id="pass1">
        //get refernce to intput fields
        var txt1 = document.getElementById('txt1');
        var pass1 = document.getElementById('pass1');

        //event handler
        var eventHandler = function(){
         if(txt1.value === ''){
         alert("Please enter a user name before entering a password");

        //create event handler, allowing for older versions of IE
        if (pass1.addEventListener){
        } else if (pass1.attachEvent) {
         pass1.attachEvent ("onkeyup",eventHandler);

-----------UPDATED CODE------------------------


All Answers

Ask Experts


Kevin Chisholm


I can answer questions about: JavaScript, Object-Oriented JavaScipt, JSON, AJAX, jQuery, HTML, CSS


I am a Front-End Web Developer living in New York City. I have provided services to titles such as,,,,,, and Being particularly passionate about Object-Oriented JavaScript as well as Web Standards, I spend a fair amount of time writing about / teaching Front-End Web Development techniques. In my free time I enjoy reading about advanced JavaScript, as well as Web Development trends and best practices. My Blog is: JavaScript-specific blog posts can be found here:

NYC Front-end Developers CSS3 / HTML5 The future of front end Front-End Engineers Javascript Syracuse University Alumni Network

Syracuse University - VPA - 1983 - 1987

Past/Present Clients

©2017 All rights reserved.

[an error occurred while processing this directive]