ab11
ab11

Reputation: 20090

Javascript: how to bring focus to an element, and show a warning message

Preface, I really don't know javascript at all.

I am trying to validate the email address of a form. If validation fails, I would like to focus on the invalid email field, and show a warning message. The below code properly returns true or false if the "focusElement" line is removed. However, it always returns true with that line included (presumably because the line is invalid and the code does not execute. Is there a proper/simple way of focusing on this element and showing the message?

function validateForm(formElement) 
  {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    if(emailPattern.test(formElement.tfEmail.value))
    {
        return true;
    }
    else
    {
        focusElement(formElement.tfEmail,'Please enter a valid e-mail address.');
        return false;
    }
  }

Upvotes: 1

Views: 539

Answers (4)

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

You should try use jQuery and jQuery Validate for this task.

jQuery is the most used JavaScript framework, it can simplify a lot of any tasks in JavaScript.

jQuery Validate is a very used plugin for validation, based on jQuery.

Upvotes: -1

Chris
Chris

Reputation: 4471

function focusElement(el, message) {
    alert(message);
    el.focus();
}

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Try:

alert("Ur err msg");
document.getElementById("yourEmailFieldId").focus();

Upvotes: 1

James Hill
James Hill

Reputation: 61812

Use .focus() and alert()

...
else
{
    alert('Please enter a valid e-mail address.');
    formElement.tfEmail.focus();
    return false;
}

If you would like the functionality to be in a separate function like your example:

...
else
{
    focusElement(formElement.tfEmail, 'Please enter a valid e-mail address.');
    return false;
}

function focusElement(obj, msg)
{
    alert(msg);
    obj.focus();
}

Upvotes: 2

Related Questions