How to set focus of ICEFaces component after initial rendering? - focus

I have a complex ICEFaces XHTML page that renders certain components conditionally, based on flags set as the user enters data on the page. What I'd like to do is direct focus to a certain field as soon as it appears, which may not be during the initial render of the page.
The ICEFaces documentation suggests that I can do this using the focus attribute of the outputBody component. Specifically:
If you setting the initial focus, the focused component must be rendered on first render call, if not then set the focus attribute only when the component gets rendered.
This seems to suggest that I can manipulate the value of the focus attribute at the time that my conditional component gets rendered. However, I don't see any attributes of the inputText component that allow me to change a value at the time the component is rendered.
Am I misreading the documentation? When and where can I alter the value of the focus attribute of outputBody so that my conditionally-rendered field gets the input focus when it appears? Or am I using the wrong tool to solve this problem?

Maybe you can use this
JavascriptContext.applicationFocus(FacesContext.getCurrentInstance(), "form:fieldM");

You can use some Javascript to set focus on an element.
Here's the Java snippet required to do this:
JavascriptContext.addJavascriptCall(FacesContext.getCurrentInstance(),
"document.getElementById('myForm:myTxtBox').focus();");
myTxtBox is the ID of your form element, and myForm is the ID of your form.
You can use this wherever you are changing certain variables' values to render/hide fields.

Due to the fact that I'm using both Seam and ICEFaces, I was not able to invoke Javascript reliably from my server-side Java code. I was, however, able to add the necessary Javascript in-line in my XHTML, within the ui:component that was being conditionally rendered, close to the input field I needed the focus to go to. The relevant section of my XHTML looks like this:
<ice:panelGroup id="textPanelInput" >
<ice:form id="textInputForm" partialSubmit="true" style="vertical-align:middle;">
<ice:inputText id="textInput" valueChangeListener="#{appField.valueChangeListener}"
size="#{appField.fieldDefLengthAsInt}"
value="#{appField.value}"
styleClass="fieldStyle" rendered="#{appField!=null}"
>
</ice:inputText>
<ice:message id="jo" for="textInput" />
</ice:form>
</ice:panelGroup>
<script type="text/javascript">document.getElementById('panelsFields:0:textInputForm:textInput').focus();</script>
The Javascript line at the bottom is the line I added to solve my problem. All of the code above is in a ui:component block that may or may not be rendered, based on other conditions. When this ui:component block is rendered, my Javascript goes with it, and sets the input focus to my desired input field.

ICEfaces supports javascript api which has setting focus function. Thus you may use it like in the next excerpt:
<script type="text/javascript">
jQuery(document).ready(function () {
ice.applyFocus(elementId);
});
</script>
elementId is jsf component clientId.
ICEFaces javascript Api

Related

ASP.Net MVC Getting hidden field value in javasccript

I have asked this same basic question before several times without a response, but let me try one more time, breaking it down as simple as possible.
I have a strongly-typed view with a hidden field on it.
When the view renders server-side, I am setting the value of the hidden field to a property of the model.
When the view renders client-side, I want to get the value of the hidden field (that was set during the server-side render) and display it in a java script alert box.
This should be a simple thing to do and yet I am unable to make it work. I have set a break-point in the view and I can see that the hidden field is being set to the correct value. But the javascript will not display that value.
The page/view being rendering has been gone to before. At the time I want to display this alert, I am going back to that page and now I want to see the alert.
It is as if the page is being cached, so instead of using the new value for the hidden field it is using the old value (from the first time the page was visited). If the DOM is being cached, how I can prevent that so that each time I visit the page I get the updated values of the page and not the cached ones? What am I doing wrong??
#<input type="hidden" id="hdnShowMsg" value="#Model.ShowMsg" />
<script>
alert($('#hdnShowMsg').val());
</script>
Your script may be firing before your document is fully rendered. Use the jQuery document ready function.
http://api.jquery.com/ready/
<script>
$(function() {
alert($('#hdnShowMsg').val());
});
</script>
Also note that document ready is not supported within a jQuery Mobile document and you may run into problems depending on what part of the DOM you are trying to manipulate.
Use $(document).bind("pageinit", function() {}) instead.
http://jquerymobile.com/demos/1.2.1/docs/api/events.html

making unobtrusive validation work when using Select2 ASP.NET MVC

Select boxes converted to Select2, do not automatically integrate with unobtrusive validation mechanism in ASP.NET MVC framework.
For example, on a form which contains a regular select box (marked as required in model definition), submitting the form while no options have been selected in the select box, will cause the border and background of the select box to take a reddish color, and by using #Html.ValidationMessageFor, error messages, if any, can be displayed beside the box. However if the select box is converted to a Select2 component, then none of the mentioned features work any more. Even the validation error message will not show up.
It seems that the reason for even the validation error message not showing, is because Select2 changes the display CSS property of the original select box to none (display:none), and I guess the unobtrusive validation script does not bother generating error messages for invisible fields.
Any ideas / solutions?
This issue isn't really specific to Select2, but rather to the jQuery unobtrusive validator.
You can turn on validation for hidden fields as highlighted in this answer.
$.validator.setDefaults({
ignore: ''
});
As the comments noted, it didn't work inside an anonymous callback function within $(document).ready(). I had to put it at the top level.
I've run into similar issues with the select2 plugin. I don't know exactly which features you're using specifically, but in my experience, when you set an element as a select2 in the document.ready event, the plugin will change some of the element's attributes on the fly (inspect one of the elements after your page has finished loading - oftentimes you'll see the id and class properties are different than what you're seeing when you view source).
It's difficult to offer more without actually seeing the code, but here's a few ideas to get you started:
First off, obviously make sure you have the a link to your select2.css stylesheet in the header.
Then, since you're talking about form submissions, I'd recommend you examine whether or not you're getting a full postback or submitting via AJAX (if you're using jQueryMobile, you're using AJAX unless you override it in the jquerymobile.js file or set a data-ajax="false" in your form attributes). You can just look at the value returned by Request.IsAjaxRequest() for this. Obviously if you're submitting via ajax, you won't hit the document.ready event and the select2 won't initialize properly and you'd need to figure out a way around that. Try refreshing the page after the submit and see if it renders the select2 component.
Then I'd suggest examining the elements and see if they're not behaving like you'd expect because you're actually trying to work with classes that the plugin has reassigned at runtime. You can either just adjust your logic, or you can dig into the select2 code itself and change the behavior - it's actually fairly well-documented what the code is doing, and if you hop on the Google group for select2, Igor is usually pretty quick to follow up with questions.
like this
$('select').on('select2:select', function (evt){
$(this).blur();
});
$('body').on('change', 'select.m-select2', function () {
$(this).blur();
})

Integrating Django-dynamic-formsets with JQuery Mobile's Radio Buttons

I am using Django and the django-dynamic-formset plugin to generate a JQuery Mobile (JQM) site. I have nested forms that allow the user to click a "Add" link to another line to the form. This works great without JQM, but when JQM is used to style the form widgets the radio button labels do not trigger the correct radio button.
I have put up a static example of the behaviour, based on the generated HTML. Click the "Add" link, then try choosing a severity for the added item. The "for" attributes of the labels appear to update correctly, so I do not know what I'm doing wrong.
The django-dynamic-formset guide provides me with a way to call a JavaScript function after the user clicks the "Add" button, but I do not know if there's a JQM method I should be calling that will fix the issue. When I use JQM's enhanceWithin function it triggers a page load, which submits my form to Django, which I don't want at that point because the form won't validate yet.
Edit: I uploaded a much better example to the same URL.
After enough caffeine and peanut M&M's I have figured it out.
Reason for Failure: The django-dynamic-formset (DDF) plugin duplicates the form you give it. But the form is cloned as-is, which already includes all the JQuery Mobile (JQM) processing. This causes JQM to ignore it and makes the radio buttons misbehave.
The Solution: The DDF plugin allows you to specify what form to clone by its formTemplate parameter. JQM allows you to disable automatic mobile-enhancement of certain elements. Create an un-enhanced version of your form, and pass that to DDF as your formTemplate.
More Details:
I put this coded into my HTML head, before the reference to JQM:
<script>
$(document).bind('mobileinit',function(){
$.mobile.ignoreContentEnabled = true; // required for using the natural forms
});
</script>
And included this style to hide my "natural" form:
<style>
.natural-form { visibility: hidden; display: none; }
</style>
In the Django code I added a <div class='natural-form> and put a dummy version of my form in it (being sure to surround it another <div> with a unique ID for reference later). In my initialization of DDF I give it the unique ID as the parameter to formTemplate.
I was told on another forum I would have to hack DDF and JQM to get this to work. I am impressed at the design of both of these libraries - flexible enough that a newbie to JQuery can stick all the pieces in the right places and get something out of it.

JSF : Disable drop down does not set value to backing bean

I have a requirment in which I need to disable a drop down on certain event through JavaScript and then submit the form. The problem is that when the drop down component is disabled the value in the drop down is not set through the backing bean.
I tried to disable the drop down componenet through div and span but it has not worked.
Can anyone suggest how can I submit the value of a disabled compoement to the backing bean?
OR do i really need to idsable that component, I mean how can I achive this using div or span?
Chapter 17.12.1 of the HTML forms specification says the following (emphasis mine)
17.12.1 Disabled controls
...
When set, the disabled attribute has the following effects on an element:
Disabled controls do not receive focus.
Disabled controls are skipped in tabbing navigation.
Disabled controls cannot be successful.
...
Note the last point. In other words, they are never submitted to the server. Thus, the behaviour you're seeing is fully correct and expected as per the HTML forms specification.
To achieve your requirement, you need to disable it after submission.

Set focus on on ASP.NET MVC model errors

I've got a model that does some validation checking and adds the errors to ModelState:
ViewData.ModelState.AddModelError("mycontrol", "message")
They display fine on the view side, but is there a way to set the focus to the control that corresponds to the validation message? Right now, the page refreshes and stays at the top of the page, so if the error is towards the end of the page, it's not obvious to the user what happened.
Note: Another solution would be for ValidationSummary to show the list of errors at the top of the page, but I've never been able to get it to display anything. All my errors are displayed via ValidationMessage.
Edit: I found my problem with ValidationSummary. The markup I had was:
<% Html.ValidationSummary()%>
which should have been:
<%=Html.ValidationSummary()%>
I'd still like to know how to snap to the field with the error however.
Some jquery goodness to scroll to the first input with an error. The tricky bit is that you have to get the underlying DOM element BEFORE you invoke focus() as the focus() method on a jQuery object fires the focus event instead of giving focus to the element.
<script type='text/javascript'>
$(document).ready( function()
{
var input = $('.input-validation-error:first');
if(input)
{
input.focus();
}
});
</script>
You could use JavaScript to find the input elements on the page that have the MVC validation HTML class (input-validation-error) added, and move the carat to the first one. That /should/ move the screen to that element although I haven't tested it.
A JS library such as jQuery will make this straightforward to do.

Resources