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);
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.
Can someone explain to me what i am doing wrong in this code?
http://jsfiddle.net/14njfqef/
var isLoggedIn = function(state){
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else(state == false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
onload=function() {
isLoggedIn(false);
}
On load i want the divs to hide but then when i click the button i want the divs to show?
Is the boolean function set out in the correct way?
Piece below tries to re-arrange piece at OP. onload not appear clearly defined , not addressed , though could be attached to an event , i.e.g., window.onload = onload . Wrapped blocks in jquery .ready() event . Removed js onclick markup from html , included at script element , or loaded from file at jquery .on("click") event . Added strict comparison operator === (an added =) to if / else if statements. Changed input type to button. Added if to else portion of composition (see link posted at comments by Felix Kling).
Try
$(function() {
var isLoggedIn = function(state){
if(state === true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else if(state === false){
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
};
isLoggedIn(false);
$("input[type=button]").click(function() {
isLoggedIn(true)
})
});
jsfiddle http://jsfiddle.net/guest271314/14njfqef/3/
changed your html to
<input type="submit" value="Boolean" id="toggle"/>
rewrote your js as
// JQuery run at start effectivly
$(document).ready(function() {
function isLoggedIn(state) {
if(state == true) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else {
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
}
// JQuery attaching a click event using an anonymous function
// and hard coding your isLoggedIn to true, passing variables is a bit more complicated.
$('#toggle').click(function() {isLoggedIn(true)});
isLoggedIn(false);
})
Well there's a few things I am not sure if you are aware of so I feel there's some responsibility on my end to make sure they are mentioned. They are a number of syntactical errors in your post that are stopping this from working so instead of addressing them I feel its necessary to update your view on what JQuery you are using as well as your selector choice.
First I would add a class structure to all of the div's to target them all at once so you can save on some lines of code. In production it's always better to have less code for all of your visitors to download because even a little bit of code can get out of control after enough hits on a webpage. Having to serve it kills speed and so does having to process three separate jquery selections as opposed to one.
I would change the HTML to...
<body>
<div id='content-container' class='boxes'>
Content Container
</div>
<div id='account' class='boxes'>
account
</div>
<div id='account2' class='boxes'>
account2
</div>
<input id="validateButton" type="submit" value="Boolean">
</body>
This way you can simply target all divs with $(".boxes"); ... I wouldn't recommend getting into the habbit of using $("div");
Next I would change the JQuery to being more JQuery friendly code. Its not always useful to use an onload event from pure Javascript to handle JQuery driven functions in correct time to the loading of DOM objects. Therefore you should use $( document ).ready( handler ) to handle this load event properly just in case it causes you problems down the road. The more common shorthand of this ready event is a simple $(function() { }); wrapper.
The rest of the code can be re-arranged to this....
var isLoggedIn = false; //<--Instantiate to false, make global to window level scope
//Load event Corrected For JQuery
$(function() {
$(".boxes").hide(); //<--Hide on load
//Add A Proper Updated Click Event To Button
$("#validateButton").click(function() {
isLoggedIn = true; //<--Should include real functionality not hand coded to true
checkLoginAndRespond(); //<--Validate Login Status
});
});
function checkLoginAndRespond() {
//If Logged, Show
if(isLoggedIn) {
$(".boxes").show();
//Else Don't
} else { $(".boxes").hide(); }
} //end function
Lastly, the version. New versions of JQuery have not been released for some time and seem to not be in the making so its a safe bet to use their most recent versions as it has thousands of pages of help for its syntax and it's very stable. I would recommend anything in the 2.0 or higher series JQuery.
I am assuming you have JQuery library loaded. Try
if (state) {
$("#content-container").show();
$("#account2").show();
$("#account").hide();
}
else{
$("#content-container").hide();
$("#account2").hide();
$("#account").show();
}
to solve your problem.
Is it possible for a button to call a function that would 'prettify' a dynamic <code><pre>? I can't get it to work.
After the page loads, the initial <code> is prettified(?), but when I change it and call prettyPrint() afterwards, it no longer works.
Example: http://jsfiddle.net/uwBjD/2/
Edit: Sorry, I was using a local prettify.js. Updated it, still encountered the same error.
Apparently after the code is prettified, an additional class is added which is prettyprinted. Anything with the class of prettyprinted is not re-prettified. You need to remove that class before recalling the function:
$('input[type=button]').click( function() {
$("#jsExample").text(" var user = 'private'; //Do NOT store your API Key on a script.")
.parent().removeClass("prettyprinted");
prettyPrint();
});
http://jsfiddle.net/uwBjD/3/
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!
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.