Javascript onfocusout problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • silpa
    New Member
    • May 2007
    • 20

    Javascript onfocusout problem

    Hi,

    I have placed two text boxes(server side) for Name and Age in asp.net 2.0.
    Their ids are txtPatientName and txtPatientAge.
    The validation to be done is both text boxes should not be left empty.

    I have written two javascript functions as follows.
    [code=javascript]
    function isName()
    {
    var str = document.forms[0].txtPatientName .value;
    if (str == "")
    {
    document.forms[0].txtPatientName .focus();
    alert("The NAME field is blank.Please enter name.")

    return true;
    }
    }

    function age()
    {
    var age=document.fo rms[0].txtPatientAge. value;
    var name=document.f orms[0].txtPatientName .value;
    if (age== "")
    {
    alert("The age field should not be blank");
    return false;
    }
    }
    [/code]

    In default.aspx.cs file, I have written
    [code=c]
    protected void Page_Load(objec t sender, EventArgs e)
    {


    if (Page.IsPostBac k == false)
    {
    txtPatientName. Attributes.Add( "onfocusout ", "Javascript:isN ame()");
    txtPatientAge.A ttributes.Add(" onfocusout", "Javascript:age ()");
    }
    [/code]
    Problem I am getting: When name is not given and if we click TAB,it is first showing alert as “age should not be blank” and then it is showing alert as “name should not be blank”.

    What I want is:When name is not given and if we click TAB, then it should show alert as “name should not be blank” and focus should be on “name” textbox.Then it goes to age textbox.
    After this, When age is not given and if we click TAB, then should show alert as “age should not be blank” and focus should be on “age” textbox.


    Plz help me in this regard by sending sample code.

    Thanks
    Silpa
  • Shaileshsharma
    New Member
    • Jun 2007
    • 26

    #2
    Hi,
    Try to do like this i think this will work as you want


    function ------- ()
    {
    if (document.getEl ementById("txtn ame").value=="" )
    {
    alert("Please Enter Name");
    return;
    }
    else
    {
    if(document.get ElementById("tx tage").value==" ")
    {
    alert("Please Enter Age");
    return;
    }
    }

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Hi there,
      The problem you're having is that you're setting the focus on the text box before you are calling the alert(). When you call the alert() your focus is changed to the alert box...it's undoing your focus().

      -Frinny

      Comment

      Working...