Quantcast
Channel: XPages – Xcellerant
Viewing all articles
Browse latest Browse all 216

Triggering a Partial Refresh when a Select2 Value is Changed in XPages

$
0
0

In my last post, I showed how to add Bootstrap error styling to a Select2. As I’ve continued to work with Select2, I came across another challenge — triggering a partial refresh when a Select2 value is changed — because standard component events aren’t executed on a Select2.

This issue is because a component is converted to a Select2 after the page loads. It takes your combobox or listbox and converts it to a div surrounding the entire field, a div for the search, and an unordered list of elements to display in the drop-down. Any event handler code that you entered on the combobox or listbox will no longer be associated with the field because it’s been replaced with the Select2 UI elements.

It is common to update a part of a page based on a value selected in any variation of a list field, so, fortunately, this issues can be worked around by using event delegation to trigger a client-side JavaScript function when the Select2 is changed.

Take this example of converting a field (with a class name of “mySelect2″) to a Select2:

$(".mySelect2").select2({
  placeholder: "Select the value..."
});

To trigger a partial refresh when the value is changed, add this code on the client load or document ready event after the previous code to enable the Select2:

	
$(".mySelect2").on("change", function(e) { 
  XSP.partialRefreshPost("#{id:myPanel}");
})

The code will watch for any change on the Select2 and it will trigger a partial refresh via client-side JavaScript. (See Mark Roden’s post on jQuery event delegation for a good explanation of jQuery event delegation.)

It must trigger a partialRefreshPost (rather than a partialRefreshGet) because it has to send the new value to the server. For the same reason, the field must be within the partial refresh target area.

You can only write client-side JavaScript code here, but if you have a larger piece of server-side JavaScript or Java code that needs to be executed, you could put that code on a hidden button (it must be rendered, but could be hidden from the screen with CSS) and trigger a click() event on that button with client-side JavaScript.

_



Viewing all articles
Browse latest Browse all 216

Trending Articles