Mirza Muneeb
Mirza Muneeb

Reputation: 136

JavaScript Events onfocus and onblur

I am trying onfocus and onblur events. It's not working. When I click the email field the value does not disappears. Here's my code. Please tell me if there's anything wrong:

    <!DOCTYPE html>
    <html>
    <head>
        <title>More Events</title>
    </head>
    <body>
        <form>
            <input type="text" value="your email" name="email" id="email" />
        </form>
    
        <script>
            var emailField = document.getElementById('email');
             emailField.onfocus = function(c) {
                if (emailField.value == 'your email')
                    {
                        emailField.value == '';
                    }
                }
             emailField.onblur = function(c) {
                if (emailField.value == '')
                    {
                        emailField.value == 'your email';
                    }
                
             }
        </script>
    
    </body>
    </html>

Upvotes: 1

Views: 70

Answers (4)

Rahul Kashyap
Rahul Kashyap

Reputation: 977

<form>
    <input type="text" value="your email" name="email" id="email" onfocus="function(this)" />
</form>

<script>
    var emailField = document.getElementById('email');
     emailField.onfocus = function(c) {
        if (emailField.value == 'your email')
            {
                emailField.value = ''; // Here was the problem use assignment operator(=) here emailField.value == '';
            }
        }
     emailField.onblur = function(c) {
        if (emailField.value == '')
            {
                emailField.value = 'your email'; // Here was the problem use assignment operator(=) here emailField.value == '';
            }

     }
</script>

Upvotes: 0

Zee
Zee

Reputation: 8488

You are using comparison operator(==) instead of assignment operator(=) here:

emailField.value == '';

Change it to

emailField.value = '';

In code:

var emailField = document.getElementById('email');
         emailField.onfocus = function(c) {
            if (emailField.value == 'your email')
                {
                    emailField.value = '';
                }
            }
         emailField.onblur = function(c) {
            if (emailField.value == '')
                {
                    emailField.value = 'your email';//Also here
                }

         }

Upvotes: 2

Arathi Sreekumar
Arathi Sreekumar

Reputation: 2574

You are using double equal to to assign:

emailField.value == '';

should be

emailField.value = '';

And in the else as well.

Upvotes: 2

Imran Bughio
Imran Bughio

Reputation: 4931

Assignment operator are wrong, change

emailField.value == '';
...
emailField.value == 'your email';

to

emailField.value = '';
...
emailField.value = 'your email';

Upvotes: 0

Related Questions