Focus on the textbox within the repeating element

I am working with a repeater that has header and item templates. The header includes a textbox and a link button labeled "Add" to add the item entered in the textbox to the list. My goal is to set the focus back on the textbox after clicking "Add". Below is the code snippet along with my attempts (which have not been successful). I have also included the OnItemDataBound for the repeater, along with a JavaScript function to set the focus client-side:

<asp:Repeater 
    runat="server" 
    ID="rptExclPBSA" 
    OnItemDataBound="rptExclPBSA_ItemDataBound" 
    OnItemCommand="rptExclPBSA_ItemCommand">
    <HeaderTemplate>
        <table style="width:300px" border="0">
            <tr>
                <td style="vertical-align:top;width:100px">
                    <asp:TextBox runat="server" ID="tbExclBox" CssClass="NormalSmall" Width="90" MaxLength="5" />
                </td>
                <td style="width:200px;">
                    <asp:LinkButton ID="lbAddExcl" runat="server" CommandName="Add" Text="Add Something" />
                </td>
            </tr>
        </table>
    </HeaderTemplate>
    <ItemTemplate>
        <table style="width:300px" border="0">
            <tr>
                <td style="vertical-align:top;width:100px;text-align:center" class="NormalSmall">
                    <%# Eval("Box") %>
                </td>
                <td style="vertical-align:top;width:200px;">
                    <asp:ImageButton ID="ibRemoveExcl" runat="server" ImageUrl="images/delete.gif" CommandName="Remove" AlternateText="Delete That Thing"  />
                </td>
            </tr>
        </table>
    </ItemTemplate>
</asp:Repeater>

In the code behind:

protected void rptExclPBSA_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        LinkButton lbAddExcl = e.Item.FindControl("lbAddExcl") as LinkButton;
        TextBox tbExclBox = e.Item.FindControl("tbExclBox") as TextBox;

        if (null != lbAddExcl && null != tbExclBox)
            lbAddExcl.Attributes.Add("onclick", "setFocusPOB('" + tbExclBox.ClientID + "');");
    }
}

protected void rptExclPBSA_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    TextBox tbExclBox = (TextBox)rptExclPBSA.Controls[0].Controls[0].FindControl("tbExclBox");
    do_whatever()
    tbExclBox.Focus();
}

Javascript:

function setFocusPOB(ctrl_id){
    var tbExclBox = document.getElementById(ctrl_id);
    if (null != tbExclBox)
        tbExclBox.focus();
}

Answer №1

After rebinding the repeater in do_whatever(), a new textbox is created, and you must locate it once again.

protected void rptExclPBSA_ItemCommand(object source, RepeaterCommandEventArgs e)
{
  TextBox tbExclBox = (TextBox)rptExclPBSA.Controls[0].Controls[0].FindControl("tbExclBox");
  do_whatever()

  tbExclBox = (TextBox)rptExclPBSA.Controls[0].Controls[0].FindControl("tbExclBox");
  tbExclBox.Focus();
}

The ItemDataBound event is unnecessary in this context.

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

Possible problem that may arise when using Express without Jade

I've been experimenting with Express for my latest project, and I came across the suggestion to use the Jade template engine for views like this: /* GET home page. */ router.get('/', function(req, res, next) { res.render('index' ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

Express, the mongoose package delivers a response of an empty array

I have encountered a common issue regarding pluralization with mongoose default model names. Despite trying various solutions, the problem persists as I am getting an empty array as the result. In my local mongoDB database, there are 2 documents in the "us ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Send the JSON output to the controller function

Hello there! I am new to asp.net mvc and I'm looking for a way to pass JSonResult data to a controller method. In my View, I have set up a table like this: <table id="tbl_orderItems" class="table table-striped table-bordered table-hover dt-respo ...

Losing track of the map function's context

I'm currently working on extending the columns in my component state array, but I'm encountering an issue with getting an undefined value. I'm struggling to figure out how to properly bind this. const data = SberData; class App extends Com ...

What is the best way to locate a function (whether it be a GET, POST, etc.) within index.js using an Express router

I've been trying to set up a router in Express, following a tutorial. However, my code can't seem to find the function get/users. Interestingly, it works fine when I include it in index.js index.js : const express = require('express' ...

The error "Unable to access properties of undefined (reading x)" occurred while using the Array.prototype.find() method

In my Typescript project, I have an array of objects and I need to extract the value of a specific key based on a matching value in another key. I want to retrieve the sheetId value of the object where the title matches the value of fileName. Here is the ...

Issue: (SystemJS) XHR error (404) encountered in Angular2 Plnkrsandbox

The issue: https://i.sstatic.net/jUKBU.png https://plnkr.co/edit/910M73kwYKc8xPlSIU57?p=preview index <!DOCTYPE html> <html> <head> <base href="/"> <title>Angular 2.1.2 + TypeScript Starter Kit</title> <met ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...

Proxy/firewall causing interference with socket connection from chrome extension

I have encountered an issue with my web app in JavaScript that connects to a socket using socket.io and a Chrome Extension that also connects in the same way to the same server. While everything works smoothly on most computers and internet connections, th ...

Unidentified event listener

I am currently facing an issue where I keep getting the error message "addEventListerner of null" even though I have added a window.onload function. The page loads fine initially but then the error reoccurs, indicating that the eventListener is null. Str ...

Verify the channel where the bot is currently active and dispatch a message

I've been attempting to set up my bot to send a message when it joins a guild, but for some reason, it's not functioning as expected. Here is what I have tried (along with some other variations): const { PermissionsBitField } = require('dis ...

Using Sequelize and Express API for verification in the controller is an essential component of building

I'm currently working on building the API for my web app, utilizing Sequelize and Express. I have set up models with Sequelize and am in the process of developing controllers and endpoints. My main query is: Should I perform data validation checks be ...

Ensuring that undefined is not present before making an API request is crucial in the componentWillMount lifecycle

When I have a component that triggers methods depending on asynchronous API requests, I check certain props using componentWillmount. If a specific prop is true, I trigger a function; otherwise, I do not. The issue arises when the prop is initially undef ...

Scrolling to top using jQuery - Problem with incorrect anchor

I am attempting to implement a scrollTop animation that scrolls to an anchor within a fullscreen <section>. However, the issue is that it does not scroll to the correct anchor on the first click. Below is the code snippet. <nav id="scroller"> ...

Having trouble accessing JSON response properties within an Angular.js controller

My Angular.js controller is called 'forecastController'. This is the code for the Angular.js Controller: weatherApp.controller('forecastController', ['$scope','$routeParams','cityService', 'weat ...

What is the best way to show a list<> in a drop-down menu?

I am working on populating a dropdownlist with a list of users. I am using the ChatUserDetails.GetPXPUsers() method to retrieve the user data. This is the code snippet that retrieves the user data: public static List<ChatUserDetails> GetPXPUsers() ...

Enhance scrolling with a bounce effect

My goal is to implement a smooth scrolling experience with a bounce effect when the user over-scrolls, meaning they scroll too much to the top or bottom. I found an answer on Stack Overflow that explains how to achieve smooth scrolling, but I also want to ...