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

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

getting information from a JSON array using AngularJS

Looking to extract all images from the imagePath array in the following JSON. While retrieving a single image works fine, encountering difficulties when trying to fetch the entire imagePath array. Any help with this issue would be greatly appreciated. Than ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

Node.js is experiencing difficulties loading the localhost webpage without displaying any error messages

I am having trouble getting my localhost node.js server to load in any browser. There are no errors, just a buffering symbol on the screen. The code works fine in VS Code. Here is what I have: server.js code: const http = require("http"); const ...

Error: The variable "$this" has not been defined in the AJAX function

Recently, I've been delving into the world of javascript and ajax. I'm trying to create a dynamic select option list similar to this: However, when attempting to compile using Google Chrome Developer tools (F12), I encounter an error like this: ...

Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process. The TypeScript co ...

Discover the most concise string within the array

Is there a way to determine the shortest string in a JavaScript array regardless of the number of elements it contains? I attempted using var min = Math.min(arr[0].length,arr[1].length,arr[2].length); to find the shortest string among 3 elements in an ar ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

Is it considered fashionable to utilize HTML5 data attributes in conjunction with JavaScript?

Currently, I am utilizing HTML5 data attributes to save information such as the targeted DOM element and to initialize events using jQuery's delegation method. An example of this would be: <a href="#" data-target="#target" data-action="/update"> ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

Add items to a fresh record using Mongoose and Express

In my model, I have an array of objects that I want to populate with new items when creating a NEW document. While I have found information on how to achieve this using findAndUpdate, I am struggling to figure out how to do it with the save() method. This ...

What is the best way to fix the Syntax error that reads "Unexpected token (1:13)"?

I can't seem to figure out why my code keeps showing errors in the browser. I'm still new to coding and learning slowly, with help from knowledgeable individuals on stackoverflow :) Card 1.jsx Syntax error:() Unexpected token (1:13) > 1 | i ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

What is the best way to integrate a Next.js Image component with a set width and an adaptable height in order to maintain the image's proportions?

This code snippet uses ChakraUI styling and retrieves images from SanityCMS: <Box w="500px" h="500px" bg="red"> <Image src={allArtPieces[0].imageUrl} alt={allArtPieces[0].title} width="500px" ...

Implementing CSS styles with jQuery

Looking for a way to dynamically add CSS attributes to different form elements like text fields, text areas, checkboxes, and dropdowns? There's also a separate block that lists possible CSS properties such as font, font-style, width, and padding. What ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Trouble with Ajax requests firing on document load in Firefox

When loading a JSP page in Firefox, I am invoking an AJAX function that calls a servlet. The servlet returns data in response. However, when I attempt to alert the data as shown in the code snippet below, I receive a null value. $.ajax({ url : 'S ...