SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Addict tlacaelelrl's Avatar
    Join Date
    Apr 2011
    Location
    Mexico city, Mexico
    Posts
    353
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Unhappy javascript won´t do what it is supposed to

    I setup a script and is working fine, however I want to use some pieces of that code, since I did not want to create repetitive lines of code I wanted to put them inside functions and then call those functions within a function, but for some reason is not working, so I decided to do a test applying that concept and here is what I did:

    Code HTML4Strict:
    <html>
    <head>
    </head>
    <body>
    <input type="text" id="myid" size="15">
    <p id="errors_console_1"></p>
    <script type="text/javascript">
    var NOnumbershere=new RegExp(/\d/);
    var thefield=document.getElementById("myid");
    var thevalue=thefield.value;
    function numbers()
    	{
    		if (NOnumbershere.test(thevalue) == true)
    			{
    				document.getElementById("errors_console_1").innerHTML = ("No numbers allowed");
    				thefield.style.background = "#FF0000";
    			}
    		else
    			{
    				document.getElementById("errors_console_1").innerHTML = ("Correct!");
    				thefield.style.background = "#FFFF00";
    			}
    	}
    function validate_text()
    	{
    		numbers();
    	}
    thefield.addEventListener("change", validate_text, false);
    </script>
    </body>
    </html>
    Supposedly that previous code should highlight the field in red and give a warning when someone enters numbers and give a “correct!” word and highlight in yellow when only letters are entered, and if updated the check should be done again right?
    But since it is not working I suppose I am doing something wrong, because it does something random every time, sometimes I enter numbers and gives me the word correct and highlights in yellow, sometimes I enter only letters and it gives me an error and highlights in red and sometimes it works fine the first check but not the second or third etc.
    Can someone help me on this?

  2. #2
    SitePoint Wizard
    Join Date
    Dec 2003
    Location
    USA
    Posts
    2,582
    Mentioned
    29 Post(s)
    Tagged
    0 Thread(s)
    Try moving:
    Code:
    var thevalue=thefield.value;
    into the numbers function. The variable is stored as a value, not a reference. This means that that variable gets the value of thefield when the script first loads, and never updates it.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •