I have a control with a listbox inside an updatepanel connected to a timer which is doing an autopostback with a scriptmanager on the main form.
To keep the item selected throughout the postback I use the below javascript. I have researched this quite thoroughly and don't believe there is another way to keep the selecteditem selected between postbacks. However this solution seems to work quite well.
My issue is that when I add a second control to the main form it won't work.
I have tried moving the javascript into the main form however I cannot access the child controls from the main form using:
document.getElementById('<%=PositionsControl.FindControl("ListBox_Candidates").ClientID %>').selectedIndex
I have also tried renaming the BeginRequestHandler and EndRequestHandler to unique names (to avoid conflicts when this script is on both control) and it will not work.
Any help is greatly appreciated.
<script type="text/javascript">
var index
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
index = document.getElementById('<%=ListBox_Candidates.ClientID %>').selectedIndex;
}
function EndRequestHandler(sender, args) {
$get('<%=ListBox_Candidates.ClientID %>').selectedIndex = index;
}
</script>
You can try to add property in code behind, that will return you value you need.
Then, in client side, just bind to this property.
Ended up going with not using Microsoft Ajax and calling webmethods from jquery instead!
Related
I have a very strange issue preventing my code from firing a JQUERY function - but only if the event is declared in an onclick attribute tag within the page's html. If that same function is assigned to an element with a javascript ".click(function()..." event, then the function is called properly and the code doesn't say "This event doesn't exist!", essentially.
I trawled through the internet looking for someone with the same issue, and while there are a lot of questions that look superficially like the issue I am having, none seem to address it exactly.
Here is an example:
//Delete an existing exclusion.
$.fn.deleteExclusion = function (idExclusion) {
document.cookie = idExclusion + "=; expires=; path=/";
$.fn.buildExclusions();
}
If I call this method by saying:
$("#someButton").click(function(){
$.fn.deleteExclusion();
)
... then the function exists and is run properly.
However, if I assign this function as follows (created on page load as part of page html):
Some Button
... then the function doesn't exist when I click that link.
This does not happen for one of my company's websites, which uses ASP.NET .aspx page structures. However, I am working on a new MVC application, which is where this behavior is occurring.
I am stumped, frankly. Right now, I am not sure what else to provide code-wise to demonstrate, without probably overdoing it with unnecessary details. Please let me know if you need additional code to help me figure this out.
You need to include Jquery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
jQuery(document).ready(function($){
$.fn.deleteExclusion = function (idExclusion) {
document.cookie = idExclusion + "=; expires=; path=/";
$.fn.buildExclusions();
}
});
We found a workaround. To get this working, we added:
//Set onclick events for delete exlusion anchor tag buttons created dynamically.
$(document).on("click", "a.deleteExclusion", function () {
$.fn.deleteExclusion($(this).attr("id").replace("delete", ""));
});
This created the onclick event on page load, but applied it to elements as they were created. It allowed elements created in our cshtml file initially, along with dynamically created html elements, to have a working click event.
I have the following scenario.
UpdatePanel
GridView
EditMode Shows UserControl with JQuery code
Inside that usercontrol I can't see the fields from JQuery. If I remove the update panel everything works fine. Most examples I've found don't seem to have a usercontrol inside the update panel. I'm not sure if that makes a difference or not. I tried using the ScriptManager.RegisterClientScriptBlock but I may have had it in the wrong place.
This worked for me, the example didn't use wildcards though, that did the trick. Since I had the control on datarows, each one had a different ID.
function BindEvents() {
$(document).ready(function () {
$("[id*='txtBox']").on("mouseover",function () {
$(this).val("DOn't leave");
var other = 0;
});
});
}
This worked for me, the example didn't use wildcards though, that did the trick. Since I had the control on datarows, each one had a different ID.
I found this question is already asked several times in different forms, but I still need some help on this, since can't get this as in the examples.
I have a JSF 2 page with PrimeFaces, and it contains the following hidden button, which I need to call on pageUnLoad from javascript.
The JSF has:
// Supposed to be hidden eventually
<h:commandButton id="doStuff" action="#{myBean.callMethod()}" />
The javascript has:
var stuff = new Object();
$(window).bind('beforeunload', function() {
stuff.doStuff();
});
stuff.doStuff = function() {
// var hidden = $("#doStuff"); // Incorrect
var hidden = document.getElementById("formId:doStuff"); // Correct
if (hidden === undefined) {
// Some logging
} else {
hidden.click();
}
}
And the managedBean has:
#ManagedBean(name = "myBean")
#RequestScoped
public class MyBean {
public void callMethod() {
// Do stuff
}
}
By debugging I can see that when manually clicking the button, it fires the event correctly.
I am also able to verify that the JavaScript is called correctly, it "seems" to find the element, and performs the '.click()' for it, but I do not catch any event on the server side.
I seem to be doing it as it has been instructed in other similar questions, but I lack the final result.
Any help would be appreciated, thanks.
Hidden button can be clicked by using JavaScript like
document.getElementById('doStuff').click();
However, you should be careful about naming containers. Hidden button must be enclosed by a <h:form> tag and prependid attribute of it should be set false. Otherwise you can access the button with the id formId:doStuff.
See also
Naming Container in JSF2/PrimeFaces
Cannot click hidden button by JavaScript
There is a much simpler way of calling server-side methods from javascript. Define a p:remoteCommand and Primefaces will create a JavaScript-function which you can call from inside your JavaScript-functions.
Use the following for defining the remoteCommand:
<p:remoteCommand name="doStuff" action="#{myBean.callMethod()}"/>
And then to call the bean-method on beforeunload just use:
$(window).bind('beforeunload', doStuff);
I've seen similar issues to this and answers but none seem to fix the issue.
I have a user control inside an update panel. Inside my user control I output javascript.
The javascript will not fire when triggered. If I move the javascript to the parent page outside of the usercontrol/updatepanels then it fires. This doesn't make sense to do this as I can't use this usercontrol on another page without either duplicating code...by either duplicating the entire javascript (different site) or adding references to a .js file in every page it's used on (same site). It's just less portable
I merely want to output the javascript with the control (inside the update panel).
The updatepanel is mentioned for accuracy of what I'm doing. It doesn't work even if I place the usercontrol outside of updatepanels.
Keeping it simple (This does not work for me):
USERCONTROL:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="_location.ascx.cs" Inherits="_location" %>
<script type="text/javascript">
function test() {
alert('Hello World!');
}
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
PARENT:
<uc1:_location runat="server" ID="_location" />
Debugging in chrome tells me "Uncaught ReferenceError: test is not defined"
If I add the javascript directly to the onclick as below, it works:
onclick="alert('Hello World!');"
And as stated above, moving the function to the parent page ALSO works.
It's as if the browser ignores the script output from the user control.
Any ideas?
When you have an UpdatePanel and that UpdatePanel updates it's content, it treats it's content as simple text/html (not code), it does not have any parser available to run the script and make it available for the page.
So this content,
<script type="text/javascript">
function test() { alert('Hello World!'); }
</script>
<a href="javascript:void(0);" onclick="javascript:test();">
Find For Me
</a>
after client side code of update panel runs and updates content of the page, the script part is not parsed - its simple text/html for the page.
This part however runs
Find For Me
because the parse of the onclick attribute is done when you click on it.
There are following workarounds available:
Move your javascript into external file
Move you script outside of the UpdatePanel
Register the script in the code behind with RegisterClientScriptBlock or alternative functions.
In Addition to the solution that Adam Wood posted, I should say that you must use ScriptManager to register the script when using update panel, at least in .net 4.0 because otherwise it won´t work.
So you can put on the PageLoad event of the usercontrol:
string script = #" alert('this is a test');
alert('it worked')";
ScriptManager.RegisterStartupScript(Page,Page.GetType(),"scriptMelhoria",script,true);
Thanks to Aristos for sending me down the right path... Though his solution works, it did not answer the question of outputting the javascript from inside the usercontrol but instead suggested moving it outside. This was not the desired outcome, as stated, as it's not kept inside the control for easier portability.
Here is my solution that accomplishes this:
CS file:
String script = "<script type=\"text/javascript\">";
script += "function test() {";
script += "alert('Hello World!');";
script += "</script>";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "locationScript", script);
One might use a stringbuilder if script is longer, but eitherway works.
This keeps the code entirely inside the usercontrol and it works from the onclick event of the a tag.
Try this;
You can find your script elements after udpdate panel callback and evaluate them.
Add a special attribute to your inline script tag to select elements after callback request.
<script type="text/javascript" data-tag='myscript'>
function test() {
alert('Hello World!');
}
</script>
And add this script to your update panel container aspx file.
<script>
if (Sys !== undefined) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endPostbackRequest);
}
function endPostbackRequest(sender, args) {
$("script[data-tag='myscript']:not([data-run])").each(
function () {
eval.apply(window, [$(this).text()]);
$(this).attr('data-run', '1');
});
}
</script>
Preferred way of dealing with javscript code that is bound to DOM elements within UpdatePanel is to subscribe to endRequest event of PageRequestManager and execute your code here. For instance you want to set click event handlers here.
// that is standard way for asp.net to execute JS on page load
// pretty much the same as $(function(){ ...}) with jquery
function pageLoad() {
// find PRM instance and subscribe to endRequest
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
}
function endRequest() {
// set all handlers to DOM elements that are within UpdatePanel
$('<%= myButton.ClientID %>').on('click', test)
}
function test(e) {
alert('Hi')
}
Alternative solution will be to use event delegation like so:
function pageLoad() {
// delegate click event on .myButton inside .container
// to the .container DOM element
$('.container').on('click', '.myButton', test)
}
And have div with a class named container around your update panel. In this case your div.container is never removed from DOM so all event handlers on it will hold after partial postbacks.
Same code without jquery and using only asp.net ajax will look like this:
function pageLoad() {
Sys.UI.DomEvent.addHandler($("myContainer"), "click", delegatedTest);
}
function delegatedTest(e) {
// since asp.net ajax does not support event delegation
// you need to check target of the event to be the right button
if (e.target.id == "myButton") test(e)
}
function test(e) {
alert("HI")
}
Good afternoon all
Here is my scenario:
I have user controls within a master page and within a user control, I may have an update panel. I have the following bit of code I place within a usercontrol that maintains various control styling during partial postback i.e. those controls affected within by an asp update panel.
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
$("select, span, input").uniform();
Indeed, when an update panel does its thing, the Fancy Dan styling is maintained.
However, I have one gripe - when a 'large' partial postback occurs, occassionally you'll see the default, generic control styling reappear breifly and then the uniform kicks in to reapply the new fancy styles.
Is there any way I can avoid seeing the nasty old, default, bland stylings?
Any suggestions greatly appreciated.
Check out working with PageManagerRequests: MSDN Working With PageRequestManager
Sys.WebForms.PageLoadingEventArgs Class
Sys.WebForms.PageRequestManager pageLoading Event
$(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(beautify);
});
function beautify(sender, eventArgs) {
// If we have event args
if (eventArgs != null) {
// for each panel that is being updated, update the html by adding color red
// to select, span, input elements
// must remember to call .html() to put html back into the panelsUpdating[i], otherwise it puts in the jQuery Object
for (var i = 0; i < eventArgs.get_panelsUpdating().length; i++) {
//My test code
//var content = eventArgs._panelsUpdating[i].outerHTML;
//var jContent = $(content);
//$("input", jContent).css("color", "red");
//jContent = $('<div>').append(jContent)
//var jContentToContent = jContent.html();
//alert(jContentToContent);
//eventArgs._panelsUpdating[i].outerHTML = jContentToContent;
//Cleaned up
var jContent = $(eventArgs._panelsUpdating[i].outerHTML);
$("select, span, input", jContent).uniform();
jContent = $('<div>').append(jContent);
eventArgs._panelsUpdating[i].outerHTML = jContent.html();
}
}
}
Edit: I think you understood that the issue was the elements were being placed into the DOM (and therefore painted) before your javascript had a chance to make them uniform(). This intercepts the UpdatePanel and uniform()'s the code prior to it inserted into the DOM
Edit 2 Alright, I've updated it a bunch, I tested this with my test code there and then included the code you're likely to add. Also, I took a short cut in eventArgs._panelsUpdating - i should really be using the get and set functions, but this works.