Is there a JQuery equivalent of ASP.Net Ajax's $find() function?
$() != $find()
There is not since $find returns the AJAX component related to the DIV element, and not the DOM element. You could build your own plugin that shortcuts the find method.
Microsoft created $find as a way to link their ASP.NET AJAX components to the DOM.
There is not a 1to1 equivalent but what you want is $('selector')
Check out the docs on the different selectors
$find('MyComponent') would be $('#MyComponent')
$find('MyComponent',div) would be $(div).find('#MyComponent')
I'd just do the following, no muss, no fuss, straight to the point.
$('#' + <%=myControl.ClientID%>)
If you want to find an element by its ASP.NET code ID rather than the generated ClientID (ctl00_RealId) then you can use this function. It just looks for elements that have an ID that ends with _{the real ID here}:
var $$ = function (id, context) {
var $ = (jQuery) ? jQuery : return ;
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
For example, say your ID in your code is pnlSuccess, say a panel:
<asp:Panel ID="pnlSuccess" runat="server"></asp:Panel>
But in the rendered code it comes out as: ctl00_content_ctl00_pnlSuccess
calling $$("pnlSuccess") will find that rendered panel.
I know it's a LOOOOOOOONG time overdue, but I think I have the kind of solution you're looking for. If I'm correct, you're looking for a $find jQuery substitute because you don't know the ID of the element (which $find doesn't have selectors as far as I know but jQuery is awesome with). I just ran into this issue using Telerik controls on a SharePoint page, so my object ID is some long crazy mess, and since Sharepoint 2010 is on .NET 3.5, I can't use a static ID.
The solution is simple, but it racked my brain for a while. $find() is searching by ID, which luckily we can return as a string through jQuery: $("elem").attr("id"). So basically what we do is use jQuery inside the $find function and it works. Here's a sample from my project:
var contextMenu = $find($("[id*=mnuContext]").attr("id"));
This worked for me, and is going to help me out a lot with the rest of my SharePoint solution.
Related
My ASP .Net page has a repeater that is loaded from AJAX. This AJAX page repeater has a column of checkboxes. The repeater is inside a html table.
<input id="chkOptionSelected" runat="server" enableviewstate="false"
type="checkbox" data-bind="click: Add" />
On the main page, I have a label whose value is computed by a JavaScript function. My view model:
function VM() {
var self = this;
self.totalSqft = ko.observable(TotalSqFt);
self.Add = function () {
self.totalSqft(TotalSqFt);
return true;
};
}
ko.applyBindings(new VM());
TotalSqFt is a global variable. The label is:
<asp:Label ID="lblTotalSqFt" runat="server" ClientIDMode="Static" data-bind="text: totalSqft"></asp:Label>
The click event computes the new total in a javascript function. All the view model needs to do is update the label with the new value.
What am I doing wrong? Is it because the checkbox is inside of AJAX content? I can see it all in the view source.
like #Jeroen said, asp:Lable will processed by server and render differently at client side.
so instead you can use normal html label and use runat="server" if you want to access it at server
check this working demo http://jsfiddle.net/91mek1tk/
The direct cause of your issue is most likely that data-bind on an asp:Label is not rendered. You would need to call Attributes.Add or something similar to add it.
Having said that, you're mixing Webforms and client-side heavy tech like KnockoutJS in a way that will probably negate the advantages you'd get from using KO, or worse cause lots of inconvenient cases like the one you're having now. I suggest either moving away from asp controls to more html-oriented controls (like you did with the first input tag), or dropping KO in favor of other, simpler client side technology (which seems more appropriate anyways, since you're currently using KO merely to handle clicks, whereas it excels mostly at two-way data-binding tasks).
Try this for your javascript function:
function VM() {
var self = this;
self.totalSqft = ko.observable("totalSqft");
self.Add = function () {
self.totalSqft("totalSqft");
return true;
};
}
ko.applyBindings(new VM());
Thank you, JAG. I tweaked the demo and got it working. I had val instead of text for my label in one of the lines and hence was not seeing the reflected value. It's working now. Thanks, everyone.
I have a web page that contains a "div" element. On the page, there is javascript to reference the div: document.getElementById('divId'). This was working fine until another developer redesigned the page to use an ASP master page.
Now, document.getElementById('divId') returns null. It appears that ASP.net prepends some characters to the names of elements within contents forms when you use a master page. How can I know what the id of the div is when the page loads?
Update Allow me to give a specific example to clarify the question: My page had a div with ID divNotice. After changing my page to use a master page, I see when I print the source to the page that renders that the div ID is ctl00_ContentPlaceHolder1_divNotice. My question is, how am I supposed to know what the div ID is going to be when the framework is done with it?
I think that this is what you looking for.
document.getElementById('<%=divNotice.ClientID%>')
to get the ID of your element as appears on the html page use .ClientID
Hope this help.
Dynamically create the javascript using Control.ClientID to determine the calculated ID of div.
document.getElementById('<%= DivControl.ClientID %>')
Or search for the element on the client side using the base ID as a search pattern. See here: A generic way to find ASP.NET ClientIDs with jQuery
I prefer the server side calculation, but if you don't do it often and/or your current design prohibits it, the client side way is a reasonable workaround.
you can check i the element exists by checking if it returns not null
if (document.getElementById('divId') != null) { /* do your stuff*/ }
in other words:
if (document.getElementById('divId')) { /* do your stuff*/ }
now you have edited you orginal question i got it.. i would do something like this:
var arrDivs = document.getElementsByTagName('div'),
strDivName = "divId";
for (i=0;i<=arrDivs.length;i++){
if( arrDivs[i].id.indexOf(strDivName) != -1) {
alert("this is it")
}
}
you can see a demo here:
http://jsfiddle.net/pnHSw/2/
i think you could do it better with a regex.
But this is a pure JS way i don't know ASP.net
edit: i think Aristos solution is much cleaner :P
maybe you can use a descendent selector un css
<div id="wrapperControler">
<controler id="controler"></controler>
</div>
wrapperControler controler{
dosomething;
}
I'm used to do doing things like this:
<a href="Javascript:void(0);" onclick="GetCommentForGeneralObservation(<%# Eval("ID") %>)">
That would be in a repeater or such like btw. However I an now trying to use unobtrusive JavaScript and hence get rid of any JS in the markup. I was trying to figure out what the best practice is in cases like this? I've used attributes and then got the value using JQuery to pass to the AJAX call but it seems a bit of a hack.
Edit in light of first reply:
I was thinking more of the
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation.
part of unobtrusive JS as I understand it.
This happens to be for an application where I don't have to worry about Javascript being turned off on the client, it's hosted internally at my company. What I was getting at was how would I get the value from Eval("ID") into the JS call if I were to attach the onclick event in a separate .js file via JQuery.
Sorry for not being clearer. I appreciate the need for progressive enhancement in public facing apps.
In HTML 5 you are allowed to define your own attributes prefixed with 'data-'
e.g.
<a
class="comment"
data-rendered-id="<%# Eval("ID") %>"
href="/getCommentForGeneralObservation/<%# Eval("ID") %>" >
And then use that attribute in jQuery in your click event handler.
$(".comment").click(function () {
var id = $(this).attr("data-rendered-id");
return GetCommentForGeneralObservation(id);
});
This will work in most pre-HTML5 browsers too as long as they support jQuery.
Note that in unobtrusive javascript you really should support non-javascript browsers, hence you need an href attribute that works as well.
I'd start with:
<a href="/getCommentForGeneralObservation/<%# Eval("ID") %>" class="getCommentForGeneralObservation">
and then attach an event handler that looked something like this:
function (event) {
var href = this.href;
var id = href.search(/\/(\d+)/);
return GetCommentForGeneralObservation(id);
};
Unobtrusive means you don't depend on Javascript for functionality and therefore your code is extended with Javascript rather than replaced by it.
In your case, you're embedding Javascript directly in the link, and worse off, the link won't work at all without Javascript enabled. Instead you'll want something like this, which is pure HTML without any reference to Javascript:
<a id="commentLink" href="comment.asp">Get Comment</a>
And your Javascript (assuming you're not using a framework) would be something like:
function GetCommentForGeneralObservation(evt) {
// Extra javascript functionality here
}
document.getElementById("commentLink").onclick = GetCommentForGeneralObservation;
With Jquery I believe you could just do:
$("#commentLink").click(GetCommentForGeneralObservation);
I'm going to re-answer this because I understand the question now and the approach I usually use is different from what has been suggested so far.
When there's no way to avoid having dynamic content, I will usually do the following:
<script type="text/javascript">
var myApp = {commentId:<%# Eval("ID") %>};
</script>
<script type="text/javascript" src="myAppScript.js"></script>
Now, in myAppScript.js, you can use myApp["commentId"] wherever you need that ID to be referenced. (I use a dictionary so as to not pollute the global namespace)
The advantage of this approach is that your myAppScript.js is still completely static and so you can serve it very fast. It also has the advantage of keeping the relevant information out of the URL and you can use Javascript objects, which can help a lot with complex and/or hard-to-parse data.
The disadvantage is that it requires inline Javascript, which isn't much of a disadvantage unless you're a web perfectionist.
I also really like DanSingerman's approach, which is more suited if your data is specific to a tag.
You might wish to use JQuery metadata plugin, or the core data function.
http://docs.jquery.com/Core/data
http://plugins.jquery.com/project/metadata
You could use the rel attribute of the anchor tag to store the value you want to associate with the link.
Click Here
Then in your jQuery code you can check the rel attribute to get the value you're looking for.
$(".comment").click(function () {
return GetCommentForGeneralObservation(this.rel);
});
(Pretty sure this is accurate for jQuery, but I'm more of a MooTools guy...)
How about making sure it is fully unobtrusive?
In the head of the HTML document
<script src="path/to/php/or/other/equivalent/server/side/file"></script>
In the path/to/php/or/other/equivalent/server/side/file:
var SiteServerVariablesEtc = {
someProperty: <?php echo "hello" ?>
}
In your normal JS file:
var myVar = SiteServerVariablesEtc.someProperty;
I wonder why I can't get value from FCKEditor with this javascript? I work with asp.net so I know the controls get different names, mine is in a placeholder and in a usercontrol. How should I approach it to find the FCKEditor?
thx
function test()
{
var oEditor = FCKeditorAPI.GetInstance('FCKeditor1');
var pageValue = oEditor.GetHTML();
alert(pageValue);
}
This should work, but the problem is that using this approach you can not have this function in external JavaScript file. It has to be inline in your asp.net page.
function test()
{
var oEditor = FCKeditorAPI.GetInstance(<%= FCKeditor1.ClientID%>);
var pageValue = oEditor.GetHTML();
alert(pageValue);
}
FCKeditorAPI.GetInstance('<%=FCKeditor1.ClientID%>')
ASP.NET generates different IDs to the ones you use based on their position within the DOM. You should use the ClientID from within the client code to get at the actual ID, but without seeing the mark-up I can't tell for sure.
i tried this code an it work
FCKeditorAPI.GetInstance('ctl00_ContentPlaceHolder1_ctl00_FCKeditor1');
i tried
FCKeditorAPI.GetInstance('<%=FCKeditor1.ClientID%>')
thing that last wont work cause i got page - usercontrol - fckeditor
so the intellesence wont show the fckeditor. i would like to make it work with the last one
so i dont have to put the "ctl00_ContentPlaceHolder1_ctl00_FCKeditor1"
I am using the example on the AJAX website for the DropDownExtender. I'm looking to make the target control (the label) have the DropDown image appear always, instead of just when I hover over it.
Is there any way to do this?
This can be done using the following script tag:
<script>
function pageLoad()
{
$find('TextBox1_DropDownExtender')._dropWrapperHoverBehavior_onhover();
$find('TextBox1_DropDownExtender').unhover = VisibleMe;
}
function VisibleMe()
{
$find('TextBox1_DropDownExtender')._dropWrapperHoverBehavior_onhover();
}
</script>
I found this and some other tips at this dot net curry example.
It works but I'd also consider writing a new control based on the drop down extender exposing a property to set the behaviour you want on or off.
Writing a new AJAX control isn't too hard, more fiddly than anything.