Jquery class and its function - c#

I am developing discussion panel in asp.net in which I am drawing some spans through javascripts
$("#commenttr").after("<tr id="+i+"><td class=\"labelPortion\"></td><td class=\"controlPortion\">" +out[i]+ "</td><td><span style = \"cursor:pointer\" class = \"plblAgreeComment\" id = \"" + ids[i+1] + "\"> Vote Up </span> <span style = \"cursor:pointer\" class = \"plblDisAgreeComment\" id = \"" + ids[i+1] +"\">Vote Down </span><span id = \"ptxtAgreeComment\" >"+ agrees[i+1] + " </span></td></tr>");
But when I am calling the jquery function
$(".plblAgreeComment").click(function(){
alert("hi");
}
Its not working. Please help me.

Description
You need jQuery .live() or .on() method to bind events to dynamically created html.
Choose .live() or .on() depending on the version of jQuery you are using.
.live() Available since jQuery 1.3. Attach an event handler for all elements which match the current selector, now and in the future.
.on() Available since jQuery 1.7. Attach an event handler function for one or more events to the selected elements.
Sample
$(".plblAgreeComment").live('click', function(){
alert("hi");
});
$(".plblAgreeComment").on('click', function(){
alert("hi");
});
More Information
jQuery.live()
jQuery.on()
Update: jsFiddle Demonstration

Use jQuery on since you are adding these items to your DOM dynamically
$(function(){
$("body").on("click",".plblAgreeComment",click(function(){
alert("hi");
});
});
on will work for current elements and future elements.
http://api.jquery.com/on/
on is available from jQuery 1.7 onwards, If you are using an older version of jQuery, you should check live http://api.jquery.com/live/

Try using .on in below syntax,
$(document).on('click', '.plblAgreeComment', function(){
alert("hi");
});
In the above code, use the table selector instead of document select.

two things.. you might have an extra character in class name when generating the html for your row.
class = \"plblAgreeCom
maybe should be:
class =\"plblAgreeCom
or you're attaching click handler before the DOM is being modified in which case:
$(".plblAgreeComment").click(function(){
alert("hi");
}
should be:
$(".plblAgreeComment").live("click", function(){
alert("hi");
}

If you want to bind events to dynamically injected DOM elements, you need to use the on method so that any new elements are bound to that event listener:
$(".plblAgreeComment").on("click", function(){
alert("hi");
}
Note: there are other methods, such as live() that will achieve similar effects, but they are being deprecated in favor of on, which handles this situation for every scenario.

Related

Using jQuery to get data attributes

Now, bear in mind I'm just trying to ensure that the code works by consuming the ready event here. I just want to make sure that the data I expect is getting pulled by jQuery. I've also tried the load event.
In the end I'd want to use the load or ready event to set the image initially and then of course use the hover event to change that image on hover.
I've tried a lot of the answers here on SO and just can't seem to get this working, so hopefully y'all can help me.
JavaScript:
$(document).ready(function () {
$("#submenumain-link").ready(function () {
alert($(this).data()["selectedimage"]);
alert($(this).data()["hoverimage"]);
});
$("#submenumain-link").hover(function () {
alert($(this).data("selectedimage"));
alert($(this).data("hoverimage"));
});
});
HTML:
<li id="submenumain-link"
data-selectedimage="some-image.png"
data-hoverimage="some-other-image.png">
But for whatever reason the alert messages just state undefined. Am I missing something here?
EDIT
Note that if I place those same alert statements in the hover, it works as expected. What event could I use to do the initialization?
$(this).data('selectedimage');
You don't need the brackets []
The real problem is that ready should not be used in this way. The ready event should only be used with making sure the DOM is ready - http://api.jquery.com/ready/
So technically, inside of document.ready, all of the DOM is ready and should be available for these kinds of things. Inside of document.ready, the value of this refers to the document element, so you need to actually grab the li element. Your code should be something like this:
$(document).ready(function () {
var li = $("#submenumain-link");
alert(li.data()["selectedimage"]); // or li.data("selectedimage")
li.hover(function () {
//alert($(this).data("selectedimage"));
//alert($(this).data("hoverimage"));
});
});
http://jsfiddle.net/XN2LV/
The issue is your .ready() call. You should use a load event if you want to wait until something is loaded but in this case it is an li element that will already exist so your code should be:
$(document).ready(function() {
var test = $("#submenumain-link");
alert(test.data('selectedimage'));
alert(test.data('hoverimage'));
test.hover(function() {});
});
It should be alert($(this).data("selectedimage"));
Look here: HTML5 data-* Attributes.

Display search result as you type in ASP.NET

I have a textbox and a literal control on my page. Whenever a user enters search text in the textbox, the HTML code with the result gets generated behind the code and gets added to the literal control.
So, now I am trying to display search result as the user types in the textbox.
Can anyone tell me how i can achieve this?
You need to look no further than jQuery UI's autocomplete for remote data sources.
For a textbox like..
<input id="birds" />
You would need to do something like..
$( "#birds" ).autocomplete({ source: "search.php" });
The rest is all just tweaking according to your needs.
I think what you want is JQuery Autocomplete. You can find it HERE.
As I understand you want to emulate Google behavior.
In this case you need to send ajax request every time when user typed new symbol in your text and substitute html. But you will need change your Literal control to some 'div' or Panel because you can't find Literal control via Javascript. It's just substituted by a html content
ex:
$('#searchbox').keypress(function() {
$.ajax({
url: "search.html",
data: { q: $('#searchbox').val() },
cache: true,
success: function(html){
$("#results").html(html);
}
});
});
It's just a sample and probably needs some corrections. But idea in it.
Handling JSON data http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});

How to make ajax update panel ? (MVC2)

I am using Telerik tree view control:
http://demos.telerik.com/aspnet-mvc/treeview
http://demos.telerik.com/aspnet-mvc/treeview/clientsideevents
What I want to do is set up this control on the left, then a "panel" on the right, that is a view that updates when the treeview is clicked.
So I want to do AJAX call to retrieve info from DB when a click is made in the tree view. Then I can update the "panel" with information on the current item.
How could I go about building this "panel" ? And any controls that are designed for ASP.NET MVC2 are better as that is what I am implementing this in. I saw something called UFRAME but it reminded me of IFRAME and thought I should probably avoid it.
Can I do this with a partial view, and then just the partial view area of the page updates ?
Thanks.
Telerik TreeView has:
OnSelect client side event that
you want to subscribe to and
issue an Ajax call when select happens
to your Asp.net MVC application controller action that
would return a PartialView which
you can then append to right panel
That's the process to be developed.
I've never used Telerik's controls in my life but based on the documentation on their page it seems that it works this way. Everything is basically the usual Asp.net MVC + jQuery except for the OnSelect client side event that you have to use. So nothing particularly complicated as long as Telerik's controls work as expected (which can be a story of its own).
Some code
Since I've never used Telerik, I still think this can be done something along the line:
You have your TreeView defined in one of your views like:
<%= Html.Telerik().TreeView().Name("ClientSideID") %>
Then use jQuery to do the rest:
$(function(){
$("#ClientSideID").bind("select", function(e){
e.preventDefault();
$.ajax({
url: "SomeURL",
data: e.item,
type: "POST",
success: function(partialView) {
partialView = $(partialView);
$("RightPanelSelector").append(partialView);
},
error: function(xhr, status, err){
// handle error
}
});
});
});
This code isn't tested but will get you started.

How to Customize Hyperlinks on Client Side in ASP.NET MVC

I need to be able to do two things with Javascript or JQuery, without involving third-party open source libraries:
Use a jQuery or Javascript function to fill the HREF attribute of a link.
Perform an HTTP Get or Post operation OnUpdate of a text box or combo box (using the above javascript function to specify the HTTP target)
The end result will be hyperlinks posted to the controller that look similar to this:
http://mydomain/addresses/1?order=name&state=ca
The controller will return a new page, ordered by name and filtered on the state of California.
Suggestions?
If you have 2 textboxes and a hyperlink with url, try something like:
$(document).ready(function() {
$('a#yourHyperLinkId').click(function(event) {
event.preventDefault();
var url = $(this).attr('href');
var order = $('input#order').val();
var state = $('input#state').val();
$.get(url, { order: order, state: state }, function(response) {
$('div#yourDivForResponse').html(response);
});
});
});
I am not sure I follow...
Why do you need to fill the HREF of the link if your going to use JQuery to do the postback anyway?
Some elements of answer here : Passing Javascript variable to <a href >
If you want to load the controller response in the window, you can use a form with a crafted action. If not, you can either use an iframe as a target to the form or use an XHR object. Whatever solution you choose, you will link it to the onchange event of the text box or combo box.
Thanks fellas for pointing me in the right direction.
Answer to #1:
document.getElementById("link2").setAttribute("href",strLink);
Answer to #2 (more or less):
$("#mySelect").change(function() {
document.location = this.value;
});

JQuery Facebox Plugin : Get it inside the form tag

I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want. The div that houses the facebox content is created outside of the tag so even though I am loading up some web controls none of them are firing back to the server.
Has anyone dealt with this that can give me some pointers?
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
and it loads up in the form tag, not sure yet if there are any side effects
You can use this code to register the PostBack event:
btn.OnClientClick = string.Format("{0}; $.facebox.close();",ClientScript.GetPostBackEventReference(btn, null));
this will let the button fires a PostBack.
Even after the :
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
change I found it problematic. When you look at the page source using firebug you see that all the html in the div assigned to be the facebox div is doubled up (repeated).
So all of those controls with supposed unique id's are doubled up on the page, that can't be good on the postback, i've decided putting asp.net web controls in a facebox is not a good idea.
I modified facbox.js to do this. Maybe there is a better solution but this works like a charm
Here what i did:
add two lines on top of facbox.js before '(function($)'
var willremove = '';
var willremovehtml = '';
find "reveal: function(data, klass) {" and add this lines before the first line of function.
willremove = data.attr('id')
willremovehtml = $('#'+willremove).html()
$('#'+willremove).html('')
find "close: function() {" and make it look like below.
close: function() {
$(document).trigger('close.facebox')
$('#'+willremove).html(willremovehtml)
willremovehtml = ''
willremove = ''
return false
}

Categories