In my JSF page I have a hidden form with an inputText, outputText and submit button. I'm using a script which on certain events fills the inputText and performs a click on the button. The button calls a method in a backing bean in which I need to do some actions and then set the value of the outputText. To do it I find the UIOutput component and set its value. In my javascript I need to perform some other action after the button is clicked but the problem is that it may take some time for the action to be completed and the outputText to be filled with the return value. So the next action in the javascript does not read the correct value. I thought of adding a change event on the outputText so to perform my action only after the value is updated but I have the same problem as this JS Events: hooking on value change event on text inputs.
So, if you were using an a4j:commandButton, you could just use the oncomplete attribute to some JS code that would execute after completing the AJAX request.
Since you are using a h:commandButton with an f:ajax, the way to do that is to use the f:ajax attribute onevent, and check if it succeeded like this:
<script>
function doWhatever(e){
if(e.status == 'success'){
doYourThingHere();
}
}
</script>
<h:commandButton action="#{someMB.someAction}">
<f:ajax ... onevent="doWhatever" />
</h:commandButton>
If you use Richfaces, you may want to take a look at a4j:ajax component, see this question.
UPDATE: removed incorrect else that assumed request didn't succeeded. See the answer to this question to see other meanings for the status attribute.
Related
I'm writing a simple single page application with Express.js. At the bottom of the page is a form, and this form is used to add users to a table, or to update a specific user. The 'submit' button will have a different function depending on the ID of the button at the time it is pressed.
Inside my document.ready function, I have 2 lines of interest:
$('#btnAddUser').on('click', addUser);
$('#btnUpdateUser').on('click', updateUser);
I also have methods that change the value of this id from #btnAddUser to #btnUpdateUser, and vice versa. I can get the ID to change. The issue is that the document.ready function doesn't seem to consider these changes.
For instance, the app starts out with the id #btnAddUser. Then I change it to have the Id #updateUser, and I can see that this works. When I press the button, though, the addUser method fires instead of the updateUser method, and I'm not sure why.
Pointy's answer should work, but this is an X->Y problem. You shouldn't be trying to toggle functionality by changing an element's ID.
Instead, store a value somewhere that says what the button should do, and then use that. You could use a data-* attribute on the button if you want:
<!-- Dynamically change data-action and value as needed -->
<input id="btnUserAction" type="button" data-action="add" value="Add" />
$('#btnUserAction').on('click', function (e) {
var action = ($(this).data("action") === "add") ? addUser : updateUser;
action.call(this, e);
});
Alternatively, you could have two separate buttons and show/hide them. Either approach should work.
You can get the effect you want by using event delegation to set up the handlers:
$(document).on('click', '#btnAddUser', addUser);
$(document).on('click', '#btnUpdateUser', updateUser);
By doing it that way, you defer the inspection of the element until the time a "click" actually happens. With your code, the elements were located at the time the handlers were assigned. After that, it doesn't matter what the "id" value is because the handler is directly associated with the DOM node (via an internal map that jQuery maintains).
This won't work, because the click event is assigned one time when ready function executes. I think the better way is to have two buttons and show/hide them instead of changing the id.
Another way would be to store the action you want in an attribute:
$('#mybutton').click(function() {
var action = $(this).attr("data-action");
if(action == "do_this")
// ...
});
And for changing the action:
$('#mybutton').attr("data-action", "do_this");
I am developing a application in MVC.
I have a view which contain another partial view.
I have textbox1 in a parent view but its value get assigned from partial view.
Now, the moment the Textbox1 get assigned with some value, I want to perform some action
like put the 10% value textbox1 value on the another textbox, textbox2 of the view.
( I want the event when textbox value get changed by code, not the manual entry.
so cant use blur() event. )
which event in jquery should I used to perform this task ?
Partials views are all processed server-side, where Javascript is not executed. Javascript only works with the full page and does not know anything about partials, so take this worry out of your question.
As already been mentioned, you need .change() and if that is not good enough, just create a function that updates value of your checkbox and do other stuff which you need doing.
//psudo-code using .trigger()
function updateTextbox(value){
$('#myTexboxId').val(value);
$('#myTexboxId').trigger('change');
}
And here another method where you create another function that updates your values and does the calculation for you.
//pseudo-code using another function
function updateMyTextbox(value){
$('#myTextboxId').val(value);
doCalculation();
}
$('#myTextBoxId').on('change',function(){
doCalculation();
});
function doCalculation(){
// update your other values
}
I'm new to CRM 2011 so I apologize if the answer is obvious. The entity I made is a form where the user fills out information, some fields are hidden until the meets certain requirements to have them visible.
Example: Were you late? Yes/No
(hidden until yes is selected)Reason:
I used javascript to make them invisible at the start and then make them visible if the requirements are met. After the user presses the save button, the field "Reason" would go back to being invisible, is there a way to make it stay visible?
Thanks
You'll have to write javascript code in the onLoad event to see if the field's values are already in a state that would result in the fields being visible. After the entity is saved, it reloads itself, incase a plugin happened to edit an attribute.
If you already attached your function to the attribute onchange event you need to add the following to your onload event:
//Will fire all functions connected to the attribute change event
Xrm.Page.getAttribute("attribute_name").fireOnChage();
Or directory call the function that implements the code i.e.
//Will only call the specified function.
ShowHideField();
Also you might find it easier to attach to onchange handlers
directly from onload code instead of the form UI i.e.
Xrm.Page.getAttribute("attribute_name").addOnChange(ShowHideField);
And to summarize:
function OnCrmPageLoad() {
var attrObj = Xrm.Page.getAttribute("attribute_name");
attrObj.addOnChange(ShowHideField);
attrObj.fireOnChage(); // OR ShowHideField();
//… more code here
}
function ShowHideField() {
// hide fields depending on yes/no questions …
}
I am working on an application where users will be evaluating a piece of art and filling out a review form as they go along. They may spend a substantial amount of time on the form, so I want to save it automatically for the user, say every 5 minutes. I was hoping I could use javascript and set a timer for the 5 minutes and then have it basically execute the entire form via ajax and I could save the data to the database in case the user gets disconnected, etc. Unfortunately I cannot seem to find any way to do this. Getting the model updated with the data is not a problem, but I can't figure out how to get it to invoke the method (similar to how the action normally would when it was submitted.) I don't want or need it to re-render anything, just let me call a method to save the data. How can I do this?
Problems implementing the solution
I tried implementing the solution of the hidden command link but I'm getting some very strange behavior. I am not sure what is causing this. First, some background on the implementation. Form #1 creates a bean (None scoped) and puts it into the flash, then redirects to Form #2. Form #2 is the big form I was writing about, where I want to implement the auto-save. Form #2 has a ViewScoped bean. In the PostConstruct for this bean, it retrieves the value from flash, and populates a property field. So far so good. This works perfectly without the javascript. I can press the command button to submit the form, and all is well. However, when I introduce the javascript, when it executes I get a null pointer exception from the variable that should have been populated from the flash by the PostConstruct. How is this javascript interfering with that? Once I have populated the property of view scoped bean with the object, it should not matter if its removed from flash scope, right? FYI if I remove ONLY the javascript code and leave everything else it goes back to working fine when I press the button to submit.
Form #1
<h:form>
... bunch of form objects ...
<h:commandButton "Start New" action="#{someRequestScopedBean.someMethod"/>
</h:form>
code for someRequestScopedBean.Method:
public String someMethod() {
// bunch of logic here
FacesContext.getCurrentInstance()
.getExternalContext()
.getFlash()
.put("myFlashObj", myFlashObj);
return "form2?faces-redirect=true";
}
view scoped bean used in form 2:
#ManagedBean
#ViewScoped
public class someViewScopedBean {
//bunch of properties here
#PostConstruct
public void initialize() {
this.myObject = (MyObject) FacesContext.getCurrentInstance()
.getExternalContext()
.getFlash()
.get("myFlashObject");
public void saveDraft() {
// save to database
}
}
Form 2 page:
<h:outputScript library="javax.faces" name="jsf.js"/>
<h:form id="myForm">
... whole bunch of fields here ...
... real button for user to submit ...
<h:commandButton value="Submit myForm"
action="#{someViewScopedBean.save}" />
... hidden button for auto-save by javascript ...
<h:commandLink id="hiddenSaveDraft" style="display: none;"
action="#{someViewScopedBean.saveDraft}" >
<f:ajax execute="#form" />
</h:commandLink>
<script>
function saveDraft() {
document.getElementById('qForm:hiddenSaveDraft').onclick();
window.setTimeout('saveDraft()',15000);
}
saveDraft();
</script>
</h:form>
Since you wrote down Javascript as one of your tags i'm going to assume you incorporate Client side Javascript code in your app.
First of all use a hidden <h:commandButton/> or a hidden <h:inputText/> ( I use the latter in cases where I need to hold some information regarding a certain variable)
In the form you are submitting add one of these:
<h:commandButton style="display:none" id="clickme">
<f:ajax execute="#form">
</h:commandButton>
<h:inputText style="display:none" id="changeme">
<f:ajax execute="#form">
</h:inputText>
In your Javascript code add this code to either click or change:
setInterval(function() {
document.getElementById("clickme").onclick();
}, 3000); // update every 3 seconds
setInterval(function() {
document.getElementById("changeme").onchange();
}, 3000); // update every 3 seconds
Both will work fine. Just make sure they are within the form you are updating.
I figured out the final solution, and the cause of problems I had implementing it the first time around. It had to do with WHEN the javascript was being fired. The script code was being fired at the exact point I placed the <script></script> block, which was before the page was completely loaded and probably before the DOM was complete. This was causing all kinds of nasty, including duplicate invocations of #PostConstruct.
I fixed it by using a javascript event listener to fire when the page was completely loaded. This is important because I am using facelets templating, and I didn't have access to the <h:body onload= attribute. The listener is a useful and elegant solution. The script block can be placed anywhere in the page. Here is what the script block looks like:
<script>
function saveDraft() {
document.getElementById('qForm:saveDraft').onclick();
window.setTimeout(saveDraft,300000);
}
function initSaveTimer(e) {
window.setTimeout(saveDraft,300000);
}
this.addEventListener("load",initSaveTimer,true);
</script>
This will invoke the hidden button every 5 minutes to save the form.
This should be fairly easy but I've tried a few things with no luck.
I have a series of Html.TextBoxFor fields on a page, each inside their own Ajax.BeginRouteForm. Next to each box I have a submit button, and this, when clicked, performs the Ajax update as desired.
I'd like to automate this so that when the user changes a value in a field (the onchange event) the form is submitted the same way it currently using using the submit button.
I tried using the htmlattributes to assign a JavaScript function to the onchange event (as shown below) and this causes the form to submit, but it redirects the page instead of working in the ajax fashion (as opposed to clicking the submit button which works correctly).
#(Html.TextBoxFor(model => answer.Value, new { onchange = "document.forms[" + answer.AnswerID + "].submit()" }));
(fortunately my answer.AnswerID is numeric and matches up with the numeric position of the appropriate form in the forms collection; I was referencing them by name but Razor (or something) was htmlencoding my JavaScript code...)
My only guess is that I'm breaking something by attaching code directly to the onchange event, but I'm at a loss as to the "right" way to hook into that event chain.
If you're willing to use JQuery, it's very simple to do:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Calling submit() on a form will ignore any submit event handlers, as seen here. You can either
call the event handler directly, or
call click() on the submit button for the form.
The former works best if you use onsubmit and return false instead of using the event argument to the callback, because otherwise you need to pass another messy object or something.