Use jQuery for find text box in ASP.NET page - c#

I have <asp:TextBox runat="server" ID="lastName" /> on a page and I want to set focus it with jQuery but it is not returning it. My code is like this:
$.ready() {
var tb = $('lastName').focus(); // don't work, why?
}

You have two different problems here that you need to resolve: a malformed selector and the fact that in ASP.NET client IDs don't match server IDs.
What you want is:
$.ready() {
$('#<%= lastName.ClientID %>').focus();
}
Let's break it down...
First, in jQuery a selector that accesses an element by it's id attribute needs to begin with a '#' symbol. So the accessor should look more like: $('#lastName'). Selectors in jQuery are similar, but more robust than in CSS. You can familiarize yourself with the selector syntax at the jQuery API site.
Second, with ASP.NET, the id's assigned to the HTML elements are often different than those that identify an asp control on the server. This is because ASP.NET needs to make sure that all elements are uniquely identified - and don't collide with names that may be defined in master pages, user controls, or repeated sections of content. These ids tend to get long and are often impossible to predict - fortunately, we can use the <%= %> code expansion together with the ClientID property of the control to insert the appropriate id for the HTML element without having to know the details of how ASP.NET assigns unique ids.
In ASP.NET 4.0, the client ID can now be specified directly, which can help avoid the technique shown above.

Here is a function I use for selecting server controls in pages that have a masterpage. It doesnt work in all cases such as nested controls but for simpler stuff its real handy.
This goes on the masterpage somewhere
<script type="text/javascript">
baseName = "<%= Content.ClientID %>_";
</script>
Using this function you can go GetServerElementById("lastname")
function GetServerElementById(id) {
return $("#" + baseName + id);
}

You can do a partial attribute query:
<script type="text/javascript">
$(function() {
$('#btnExtract').click(
function() {
alert($("input[id$='txtMessage").val());
}
);
});
Selecting ASP.NET Web Controls in jQuery

Related

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

ASP.NET set hiddenfield a value in Javascript

I don't know how to set the value of a hiddenField in Javascript. Can somebody show me how to do this?
Javascript:
document.getElementById('hdntxtbxTaksit').value = "";
HTML:
<asp:HiddenField ID="hdntxtbxTaksit" runat="server" Value="" Visible="false"> </asp:HiddenField>
error : "Unable to get value of the property \'value\': object is null or undefined"
Prior to ASP.Net 4.0
ClientID
Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.
This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.
var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
Asp.net server control id will be vary if you use Master page.
ASP.Net 4.0 +
ClientIDMode Property
Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.
asp:HiddenField as:
<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />
js code:
$("#hfProduct").val("test")
and the code behind:
hfProduct.Value.ToString();
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value
The id you set in server is the server id which is different from client id.
try this code:
$('hdntxtbxTaksit').val('test');
I suspect you need to use ClientID rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server".
E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):
var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;
If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:
.cs file code:
ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);
and then use following code in JS:
document.getElementById(hdntxtbxTaksit).value= "";
Try setting Javascript value as in document.getElementByName('hdntxtbxTaksit').value = '0';

HTML helpers in ASP.NET MVC 3 with Javascsript action

I have many HTML helper in Helpers.cshtml file, but some of the helper (html) need some jquery action, so how do i can call jquery inside helpers.cshtml, is that possible?
i know we can keep the js file in header or particular page, but i do not want to do like that, i want to use jquery or javascript only on the page which loaded particular helper.
anyone have idea on this?
My scenario is, i have list box control, that is properly loading from helper, but i need to apply custom theme to the list box.
Little more Clarity
//in index.cshtml
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
//in Helpers.cshtml
#helper testListBox(string listName, string listData){
//...... HTML code .........
//Javascript here?
}
With Web Forms, the framework could automatically include Javascript (once) when certain server controls were used on a page; ASP.Net MVC has no such facility. It sounds like this is what you're missing.
The way to do it is on the client. Look at RequireJS at http://requirejs.org/. This is a client-side library for managing Javascript dependencies. This does what Web Forms did, but better, and it does more. Your master layout will have a script tag like this:
<script src="/Scripts/require.js" type="text/javascript" data-main="/Scripts/main"></script>
This can be the only script tag you include on every page. Everything else can be dynamically loaded only as needed by RequireJS. It's true that you load this on every page, but it's smaller than jQuery, and it earns its place because it does so much for you.
Using your example, let's say you have this markup:
#Helpers.testListBox("mylist" "1,2,3,4,5,6,7")
and it renders HTML and needs jQuery scripting. You would render this:
// HTML for list box here
<script type="text/javascript>
require(['jquery'], function($) {
// Do your jQuery coding here:
$("myList").doSomething().whatever();
});
</script>
The require function will load jQuery, unless it has already been loaded, and then execute your code. It's true that your jQuery snippet is repeated once per use of the HTML helper, but that's not a big deal; that code should be short.
RequireJS manages dependencies effectively; you can have module A, and module B which dependes on A, and module C which depends on B. When your client code asks for module C, A and B will be loaded along with C, and in the correct order, and only once each. Furthermore, except for the initial load of require.js, scripts are loaded asynchronously, so your page rendering is not delayed by script loading.
When it's time to deploy your site on the web server, there's a tool that will examine the dependencies among the Javascript files and combine them into one or a small number of files, and then minimize them. None of your markup has to change at all. While in development, you can work with lots of small, modular Javascript files for easy debugging, and when you deploy, they are combined and minimized for efficiency.
This is much better than what the web forms framework did, and entirely client-side, which in my opinion is where it belongs.
You can put a <script> tag in the helper body.
How about this for an example of a partial view:
#model Member.CurrentMemberModel
#{
var title = "Test View";
}
<script type="text/javascript">
// Javascript goes in here, you can even add properties using "#" symbol
$(document).ready(function () {
//Do Jquery stuff here
});
</script>
#if (currentMember != null)
{
<div>Hello Member</div>
}
else
{
<div>You are not logged in</div>
}

problem with masterpage and jquery

I have a MasterPage that inside its content section I added a FORM element.
When accessing that page, all my controls are renamed since the FORM is runat=server.
And thus when selecting in jquery, even the form has been renamed
How can I fix that?
thanks
With a master page, all elements will have ct100__etc appended to the ID of the element. This is a feature since its a naming container. Typically, the way to work around it is to use syntax like:
$("#<%= button.ClientID %>").click(..);
To access the longer ID's, or rely on CSS classes to identify elements. Another trick is to wrap certain sections of the form with a DIV HTML element and give it an ID to target.
HTH.
You can't, that's the behavior of .Net. What you can do is adjust your jquery usage to incorporate the ClientID of the controls you're using. The easiest way is to have some sort of translation variable injected into script in the head somewhere.
<script language="javascript">
var myControl1 = '<%=myControl1.ClientID %>';
</script>
Then you can use myControl1 as a string variable to inject the client id into your jquery calls in a more readable fashion.
Have a look at this post here
http://john-sheehan.com/blog/custom-jquery-selector-for-aspnet-webforms/
Explains it all pretty clearly. the trick is to use ClientId
In addition to the .ClientID approach suggested in many of the other answers, you can use jQuery's endswith selector.
eg: Select the element whose id endswith "myid" (eg ctl001_form1_myid)
$('[id$="myid"]');
or if you are using .net 4, you can set ClientIdMode="false" to prevent the renaming.
You can use Control.ClientID for this. Something like
$("#<%= yourelement.ClientID %>")
You can also create a CSSCLASS and then access by $('.classname')
<asp:TextBox id="tb4" Text="Hello World!" cssclass="txtboxtb4" runat="server" />
alert($('.txtboxtb4').val());
Another way is put controls in span tag.
<span id="txt">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
</span>
Than you can select you element like this in jQuery.
$('#txt > input').val('Hello world');
But my way is, select element with ends with selector.
$('input[id$="txt"]').val('Hello world');
Works for my cases. Hope help.

Reading C# property into JQuery code

I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.
$(".AspNet-GridView-Normal > td > input").click(function() {
//Need to access the C# property here
//Take action here based on the value of the C# property
});
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.
Markup:
<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>
Code Behind:
hfValueINeedToKnow.Value = <some value>;
jQuery:
$("#<%= hfValueINeedToKnow.ClientID %>").val();
You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:
<script>
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = <%= AvailableInstalls %>;
});
</script>
Well you can't.
You need to render the C# property in some element (perhaps a hidden field) and then look at it that way.
But explain further: What property are you trying to check?
What I've done for this scenario in the past is to print out my code value into the markup and store whatever it is in a javascript variable, thus making a copy of it available to client-side code. This is a silly example, but hopefully it makes sense:
<%
var messsge = "Hello World!"
%>
<html>
<head>
<script type="text/javascript">
function ShowMessage()
{
var msg = '<%= message %>';
if(msg)
alert(msg);
}
</script>
</head>
</html>
There isn't a really clean way to do this. Your best bet would probably be to use the ClientScript.RegisterClientScriptBlock functionality built into ASP.NET. Here's a good primer.
private int myValue;
protected void Page_Load(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(typeof(Page),
"vars", "<script>var myParams = { p1: " + myValue + ", p2: 'My Name' };</script>");
}
This will put the supplied script on your page towards the top of the form. You can change that too. Obviously, it isn't the prettiest; you are essentially string concatenating a different language, but it will work, and for simple variable declaration isn't too rough on the eyes.
ASP Embedded in JavaScript always makes me nervous from the perspective of script injection attacks and the inability to unit-test your JavaScript.
This build upon an ealier answer:
<script type="text/javascript">
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = $("#MyHidden").val();
});
</script>
You could move it to a hidden variable:
<input type="hidden" id="#MyHidden" value="<%= AvailableInstalls %>" />
However this doesn't get around the problem of injection. So you could you could add a server-side hidden variable and set it from the Page_Load event function in ASP.NET.
(P.s. you also need the attribute type="text/javascript" in your script tag to make it valid HTML).
If you will put your value into an asp:HiddenField with id hfValueINeedToKnow, the simplest way to retrieve this value client side is
var jsvar = $("[id$=hfValueINeedToKnow]").val();
So you can also place this code in a separate .js file.

Categories

Resources