JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<object name="login" id="login" classid="CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
    <param name="DataURL" value="member.txt"/>
    <param name="UseHeader" value="true"/>
    <param name="TextQualifier" value=""/>
    <param name="FieldDelim" value="|"/>
</object>

    <script>
        var rs = login.resultset;
        function validation()
        {
            rs.moveFirst();
            while(rs.moveNext())
            {           
                if(document.getElementById("txtid")== rs(0) && document.getElementById("txtpass")==rs(1))
                {
                    alert("Login Succeed");
                    return; 
                }
            }
            alert("Email or Password Wrong");
            return;
        }
    </script>

</head>


<body>
<form>
Username: <input type="text" id="txtid" /> <br/>
Password: <input type="text" id="txtpass" /><br/>
<input type="submit" value="game start" id="btnstart" onclick="validation()"/>
</form>
</body>
</html>

The error message states: login is not defined

I am certain that it's defined! I have tried searching for solutions, but found no clue as to what might be wrong in my code :/ Can someone please help?



EDIT: Updated version of my code looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>


<body>


<form>
Username: <input type="text" id="txtid" /> <br/>
Password: <input type="text" id="txtpass" /><br/>
<input type="submit" value="game start" id="btnstart" onclick="validation()"/>
</form>



<object name="login" id="login" classid="CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
        <param name="DataURL" value="member.txt"/>
        <param name="UseHeader" value="true"/>
        <param name="TextQualifier" value=""/>
        <param name="FieldDelim" value="|"/>
</object>

<script>
    var login = document.getElementById('login');
    var rs = login.resultset;
    function validation()
    {
        rs.moveFirst();
        while(rs.moveNext())
        {           
            if(document.getElementById("txtid")== rs(0) && document.getElementById("txtpass")==rs(1))
            {
                alert("Login Succeed");
                return; 
            }
        }
        alert("Email or Password Wrong");
        return;
    }
</script>

</body>
</html>

After making these updates, I am now encountering the rs is undefined error when clicking the button. Can anyone tell me what could be going wrong?

Answer №1

Looking at your code:

> <object name="login" id="login" ...>
>   ...
> </object>
>  <script>
>          var rs = login.resultset;  

You are relying on the element with the id login to be a global variable, which is not always reliable across different browsers. It is best practice to reference elements using standard DOM methods like getElementById:

  var el = document.getElementById('login');

Furthermore, there is no standard resultset attribute for object elements and you have not defined one. Therefore, it is unreasonable to expect the DOM element returned by the above expression to have a resultset property. Before using the rs variable, it is advisable to check if it has a valid value for your intended use, for example:

    if (rs && rs.moveFirst) {
      rs.moveFirst(); 

And so forth.

Answer №2

  • It's important to remember that content should always be placed within the <body> tag and not in the <head>. The only elements suitable for placement in the <head> are scripts, styles, and miscellaneous meta-data related to your page. Anything visible on the page itself should be contained within the <body>.

  • While it's true that elements with an id attribute automatically create a global variable with the same name referencing the element, it is best practice to access elements using document.getElementById() for security purposes.

  • To ensure safe script execution, always include your <script> tags after your main content but before closing the <body> tag. This guarantees that all elements referenced by your scripts already exist on the page.


<!DOCTYPE html>
<html>
    <head>
       <!-- Title, meta information, styles, and non-DOM scripts go here -->
    </head>
    <body>

        <!-- Main content of the page appears here -->

        <object id="login">
           <!-- ... --->
        </object>

        <script>
            //Scripts that manipulate the DOM should be placed here after content

            var login = document.getElementById('login');

            //The "login" variable now refers to the object element

        </script>

    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Disable functionality not functioning properly on button attribute

I've created a demo on JSFiddle here: http://jsfiddle.net/qJdaA/2/. The goal of this code is to disable the button with the ID #monitor if no checkboxes are checked. var checked = $('#status_table tr [id^="monitor_"]:checked'); if (checked. ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: The issue arises with the autocom ...

The internet explorer browser does not support the keypress event

i have the following code snippet: <input class="any" type="text" id="myId" name="myName" /> this specific input is using a jquery datepicker plugin.. (http://jqueryui.com/datepicker/) Here is my JavaScript for this element: $('#myId'). ...

Which medium is the optimal choice for file manipulation in Node.js and JavaScript?

Is there a simple way for JavaScript to receive incoming data from Node.js that was obtained from an external server? I've been searching for a solution to this problem for days now. Here's my current approach: I plan to have both the server-sid ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

What is the best way to showcase information retrieved using the getDocs function from Firebase Firestore?

Hello! I am currently exploring the world of Firestore and facing a challenge. My goal is to retrieve a data object from Firestore, set it as state, and then display it on my application: Below are the imports that I have utilized for this task (please ig ...

Save the output of a function in node.js

I have created a function that utilizes the nodejs module recursive-readdir to read all files within a folder recursively. The function is functioning correctly, but I am facing an issue with exporting the 'routes' array using 'module.export ...

When there are numerous websocket connections in Google Chrome, Socket.io can encounter issues and break down

I am encountering an issue where I create 60 client connections to a socket.io server using Google Chrome browser. The server sends screenshots to the clients at specific times, but some of the websocket connections, which are subprotocols of socket.io, ge ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Invoking an *.aspx method from an external HTML file

Greetings, I am a newcomer to the world of web application development. I have successfully created an *aspx page that communicates with a webservice through a method returning a string. My next goal is to invoke this aspx method from a remote HTML 5 page ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

Tips for adjusting the autocomplete maxitem dynamically

I am working on a multi autocomplete feature and I have the following code. Is there a way to dynamically set the maximum number of items based on the value entered in another text field? <script> $(function () { var url2 = "<?php echo SI ...

How do I prevent a specific word from being removed in a contenteditable div using JavaScript?

Attempting to create a terminal-like experience in JS, I am looking to generate the word 'current source, current location' (e.g., admin@ubuntuTLS~$: ~/Desktop) at the beginning which cannot be removed. Also, I want to prevent the caret from bein ...

Display the div only when the radio button has been selected

I have been attempting to tackle this issue for quite some time now, but unfortunately, I haven't had any success. My goal is to display a specific div on the webpage when a particular radio button is selected. While I have managed to achieve this by ...