Skip to content Skip to sidebar Skip to footer

Send Asp.net Control Id To A Javascript Function

I have 2 views. The last control on view1 is txtName & the first control on view2 is txtAge. Need to change the focus from txtName to txtAge on TAB press, but I fail to acheive

Solution 1:

You can try setting it in server-side code:

txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');", txtAge.ClientId); 

Solution 2:

Perhaps it is sufficient to use tabindexhttp://msdn.microsoft.com/en-us/library/ms178231%28v=vs.100%29.aspx

that uses build in features rather then javascript.

if you use asp.net 4.x you can use clientidmode=static http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

<asp:MultiviewID ="multiview1"runat="server"ActiveViewIndex="0"><asp:viewID="view1"runat="server"><!-- other controls --><asp:Textboxid="txtName"runat="server"TabIndex="1"/></asp:view><asp:viewID ="view2"runat="server"><asp:Textboxid="txtAge"runat="server"TabIndex="2"/><!-- other controls --></asp:view></asp:Multiview>

edit if you do not mind using jQuery. You can wrap a div around <asp:View.. and then do something like:

$("div.view input:last-child").on("change", function(){
    $(this).parent().next().find("input:first-child").focus();
});

please keep in mind that this is pseudo code. It is just an idea.

Solution 3:

Try this and see if it's any better.

 <asp:Textbox id="txtName" runat="server" 
onfocusout='<%= String.Format("SetFocus(\"{0}\");", txtAge.ClientId) %>'></asp:TextBox>

Solution 4:

It is not possible to set an attribute using an inline block in that situation... as you can see you are getting the literal <%=txtAge.ClientId%> text, and you are not getting the processed value that you are expecting.

You have two obvious solutions...

The first one (which Yuriy has already given you in his answer) is to set it from the code behind...

txtName.Attributes["onfocusout"] = String.Format("SetFocus('{0}');", 
                                                 txtAge.ClientId);

(Disclaimer, I don't know what the MultiView is, as I've never used it, so I'm not 100% sure the 2nd option below will actually work in your scenario. Also, it is untested code.)

The other is to use what Murali provides in his answer, but with additional manipulation...

<asp:Textbox id="txtName" runat="server" onfocusout="SetFocus(this);" />

functionSetFocus(nameCtrl) {
  var ageId = nameCtrl.id.replace(/txtName/,"txtAge");
  var ageCtrl = document.getElementById(ageId);
  ageCtrl.focus();
}

Solution 5:

Change line onfocusout="SetFocus('<%=txtAge.ClientId%>');"></asp:TextBox> as onfocusout="SetFocus('txtAge');"></asp:TextBox>

You don't need to send ClientId

Post a Comment for "Send Asp.net Control Id To A Javascript Function"