The code snippet `document.getElementById("<%= errorIcon.ClientID %>");` is returning a null value

I need to set up validation for both the server and client sides on my registration page. I want a JavaScript function to be called when my TextBox control loses focus (onBlur).

Code in the aspx page

<div id="nameDiv">              
    <asp:UpdatePanel ID="updatePanelName" runat="server">
        <ContentTemplate>
            <asp:Label ID="labelName" runat="server" Text="Enter Your Name"></asp:Label>
            <asp:TextBox ID="textBoxName" runat="server" placeholder="Enter Your Name" 
              onBlur="check(this)"></asp:TextBox>
            <i class="fa fa-exclamation-circle errorSign" id="errorIcon" runat="server"></i>                      
            <asp:Label ID="labelNameError" runat="server" Text="Name can't be blank" ForeColor="Red"> 
              </asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
</div>

Javascript Code

function check(txtBox) {
    var errIcon = document.getElementById("<%= errorIcon.ClientID %>");
    txt = txtBox.value;
    if (txt.length < 1)
        errIcon.style.visibility = "visible";
}

CSS

input[type=text] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display:inline-block;
    position:relative;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}


.errorSign{
    position:absolute;
    margin-right:30px;
    left:1050px;
    top:220px;
    visibility:hidden;
}

Answer №1

The original poster has confirmed in a comment that...

yes, it's an external JavaScript file

The issue at hand is that .js files are not processed by ASP.Net and are sent to the browser as is. This means the browser receives the line exactly as it is written...

var errIcon = document.getElementById("<%= errorIcon.ClientID %>");

There are several ways to solve this problem. The first option, while not ideal, is to include the script in your .aspx or .ascx file.

This way, the script, being part of an ASP.Net processed page, will have the actual id of the control instead of <%=..%>.


The second, and perhaps better, approach is to directly use the class name instead of the id...

var errIcon = document.getElementsByClassName("errorSign")[0];

Since getElementsByClassName returns an array of elements (as multiple elements on the page can have the same class), the above code will target the first item in that array. If your code is more complex, you may need to adjust it accordingly.


Another option (credit to @epascarello) is to use nextElementSibling, although this method may break if the HTML structure is altered for any reason (such as a page redesign)...

var errIcon = txtBox.nextElementSibling;

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

Is it possible to show a Windows.Form.MessageBox in an ASP.NET web application?

To ensure a better user experience, I am looking to enhance the way my validation error messages are displayed. Currently, when a user clicks on a Button control without entering text in the corresponding TextBoxes, a MessageBox is shown with the necessary ...

Is it possible to invoke a Javascript function from a coffeescript file?

Struggling to invoke a javascript function from a Coffeescript file within my $(document).ready(), but it seems like the function is not being executed. The function I intend to call originates from an external source that I have included in the head sect ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

EMFILE error encountered while attempting to initialize a new react-native project and watch file changes

Looking to start a new react-native project? Here are the steps: Begin with react-native init testproject then run react-native run-ios Encountering an error while watching files for changes: EMFILE {"code":"EMFILE","errno":"EMFILE","syscall":"Error watc ...

"Running 'npm run build' in Vuejs seems to have a mind of its own, acting

Recently, I completed a project and uploaded it to Github. The issue arises when I attempt to clone it to my live server - only about 1 out of 10 times does everything function correctly after running npm run build. My setup consists of Ubuntu 16 with ngin ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Ways to determine if an object contains an array

Looking at the following data structure: [ 13, { a: [ [ '2988.30000', '0.19000000', '1549294216.653040' ] ] }, { b: [ [ '2988.30000', '0.00000000', '1549294216.653774&a ...

Displaying a Bootstrap modal with empty editing information

I am facing an issue with my modal bootstrap where the data is not loading into the bootstrap even though it is being passed from the controller. The Grid on my page pulls in data from a list for Notes Object @foreach (var notes in Model) { <tr> ...

Steps for including a subdocument within a mongoose schema

I am currently working on setting up a subdocument within a mongoose schema using node.js/Express. There are two schemas in play: Member and Address Member.js // app/models/member.js // Loading mongoose to define the model var mongoose = require(' ...

Blurred entities aligning in front of one another (THREE.JS)

While experimenting with three.js, I encountered an issue with objects appearing fuzzy when they overlap. The distortion looks like this. Can anyone provide assistance with this problem? Below is the code I'm currently using: // Initializing basic o ...

Encountering difficulty in creating a Nuxt website using @googlemaps/js-api-loader

While using the @googlemaps/js-api-loader in my Nuxt 3 website, I encountered an issue. Everything worked perfectly during local development. However, when I attempted to build the project with nuxt generate (whether locally or on Vercel), I received the f ...

Unable to access data from the Array by passing the index as an argument to the method

Having trouble retrieving an item from an Array using method() with an index argument that returns undefined export class DataService { public list = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, ...

methods for pausing music through a toggle button in a React JS application

I am facing an issue with the following shortcode for playing a song on a toggle button. The problem occurs when I try to pause the music and it does not stop as expected. import { React, useState } from 'react'; import './audio.css&apos ...

Position divs to be perfectly aligned and centered

I'm in the process of creating a webpage and facing challenges with aligning my divs properly, specifically the animated company logos. I want them to be positioned side by side rather than on top of each other, with space in between to fit the layou ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

The console experienced a forced reflow when a tooltip appeared on the slider handle while executing JavaScript

I am currently facing an issue with my web page that includes various elements along with the Ant.design slider. The values of the slider are being controlled through React states. However, I have noticed that when the slider tooltip is enabled, the respon ...

Deconstructing JavaScript scripts to incorporate HTML5/CSS3 functionality for outdated browsers such as Internet Explorer

I have been researching various resources and guides related to different scripting libraries, but none of them seem to address all the inquiries I have regarding performance and functionality. With so many scripts available, it can be overwhelming to dete ...

Implementing jQuery autocomplete on dynamically generated fields post page load

I have successfully implemented jQuery UI Autocomplete to fetch data from a DB and populate a form dropdown. However, I am faced with the challenge of adding more form fields dynamically that also need to have the autocomplete feature applied to them. Is ...

"Combining JSON, JavaScript, and HTML for dynamic web development

I am a junior computer programmer facing challenges with our JSON project. The objective is to store an object in local storage, but my HTML and JS code are not working as intended. It seems like nothing happens at all. Any suggestions or feedback would ...