how to change select2 value programmatically - jquery-select2

I have a select2 box in bootstrap modal, I want to change the value of the select2 box but it didn't work.
I tried every single solution in previous posts and results but none of them got it work.
I use select2 4.0.2, I tested:
$('#select_id').val('val').trigger('change.select2');
$('#select_id').val('val').trigger('change');
$('#select_id').val('val').change()
It works one or two times then it stops working (randomly)
It works fine only when I change the select2 back to 3.x.x

$('#select_id').val('val').trigger('change');
is the right way, see here

$('#select_id').select2('val', selectedValue);

For Select2 with Ajax call, I struggled with lot of options, but none worked. Then i came to following solution, which works like charm
$("#select_id").html($("").val('val').text('text')).trigger("change");

To programmatically select an option/item for a Select2 control, use the jQuery
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
You can also pass an array to val make multiple selections:
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

I have used the following code in 4.x.xx version and it is working
$('#select_id').val('val').select2();

If you, like me, have added a custom handler for the select2:selecting event the correct complete answer to changing a value and triggering the custom select2 event would be:
$('#select_id').val('val').trigger('change').trigger({
type: 'select2:event_name', // It worked for me with select2:selecting and select2:select
params: {
args: { // Only use 'args' if using select2:selecting, select2:select does not use it
data: varWithEventData
}
}
});

For those who facing an issue like this:
If you're using multiple select elements and have a common event handler (like $(".mySelect2Inputs").click(...) ) when you do $('#mySelect2').trigger('change') the click event handler is gonna trigger multiple times ($(".mySelect2Inputs").length times).
To prevent this situation, you must use $('#mySelect2').trigger('change.select2') (attention to .select2 namespace!).
From the select2 docs:
https://select2.org/programmatic-control/events#limiting-the-scope-of-the-change-event
It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. To limit the scope to only notify Select2 of the change, use the .select2 event namespace:
$('#mySelect2').val('US'); // Change the value or make some change to the internal state $('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes

Related

jQuery autocomplete programmatically search and SELECT first choice (if any)

This should have been pretty straight-forward, but none of the solutions in StackOverflow doesn't seem to work for me...
Using jQuery 2.1.0, I've set up an autocomplete using an Ajax source, autoFocus: true, and a select: function (event, ui) { ... } to provide me with key/value pair combinations.
As soon as I start typing in the input field, I get the correct options as a DDL, which I can then select using the mouse.
However, I would now like to programmatically trigger the autocomplete search, and then SELECT the first option (if available).
I trigger the search like this:
Preparer.autocomplete('search', LoginName);
The available choices show up correctly, but I can't seem to be able to select the first one programmatically!
I tried calling .select(), I've tried triggering keypress 13 and 9 within the control, and even tried performing the actions within a setTimeout function to make sure that the dialog was rendered correctly!
I even tried setting the option { selectFirst: true }, but still nothing...
Is there something else I could try??
As in the comment above:
You can trigger a click on the first menu item:
$("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren().first().cl‌​ick()
Keep in mind: Triggering a select will also close the menu, which seems counterintuitive. It'd be better to intercept the data in source and trigger your custom callback there, and not bother with select at all.
Search
$('#autocomplete-id').data("uiAutocomplete").search($("#autocomplete-id").val());
&
Select
var results = $("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren()
.first().cl‌​ick()

text change event sj:autocompleter struts2 jquery

Here is what I am trying to do.
If the user makes a selection from the suggested options then I display a div tag using jquery. I use onCompleteTopics to fire this event.
Now when the user makes any changes to the text box I want to hide the div tag again unless the user makes a selection from the suggested options.
How to fire the text changed event on jquery struts2 autocompleter.
I make a div tag visible when the user selects something from the suggestions using onCompleteTopics.
However if the user changes the text in the field I want to hide the div tag again.
But I am not able to find the right event for the same.
After trying a lot of permutation and combination I managed to figure out the solution. Its not straightforward maybe not the ideal solution but it works.
Struts Code
<sj:autocompleter
theme="simple" name="userName" id="idautocomplete"
href="%{fetchList}" onSelectTopics="complete" onSearchTopics="textchange"
loadOnTextChange="true" loadMinimumCount="3" />
Note I have used onSelectTopics and onSearchTopics but this itself do not solve the problem. I have to use some jquery along with this.
jquery
var gvar;
$.subscribe("complete", function(event, data) {
gvar = data;
setTimeout(delayfunc, 0);
});
$.subscribe("textchange", function(event, data) {
$('#idBizAccess').css("display","none");
});
function delayfunc() {
$('#idBizAccess').css("display","table-row");
}
The unusual part here is setTimeout with delay 0. I tried calling the function directly but it doesn't fetch the selected value instead it just fetches the value that is typed in the autocompleter field.
Now it works as per the requirement.

How do programatically change the attributes of <sj:tabbedpanel>

I am using Struts jQuery plugin. Problem is with <sj:tabbedpanel>.
I want to preselect the tab depending on the input while loading the page.
I know there is property selectedTab="1".
But I want it to change it while loading the page using jQuery.
In jQuery-UI plugin, there is function $("#tab").tabs('selected',2) which does that.
What is the similar function which does the same thing here.
Try this:
<sj:tabbedpanel id="tabbed" selectedTab="%{selected}"></sj:tabbedpanel>
selected should be a parameter, which decides the opened tab.
If you still wanna use jQuery, please check the api: jQuery Tabs API
here is the important part:
A series of events fire when interacting with a tabs interface:
tabsselect, tabsload, tabsshow (in that order)
tabsadd, tabsremove
tabsenable, tabsdisable
If you want to do this from javascript then use option to set selected tab.
$("#tab").tabs( "option", "selected", 2);

Zepto's on implementation for Focus and Blur events

I need to run some code on focus and blur events on elements that were injected into the DOM after page load. So I am using Zepto's on (Zepto's on link) to run the code but it doesn't work for me.
Here is my jsfiddle in which I am trying to make it work - http://jsfiddle.net/ashfame/zR2xL/
Your on declaration was a little off in the original JSFiddle. When you use the .live() "version" of .on() you select the document with Zepto (because, I believe, that's what the .live() function does behind the scenes) then apply the .on() method and pass it the parameters event, selector, and function. It looks something like this:
$(document).on(event, selector, function);
Check out this JSFiddle that I modified a bit from the one you posted in the comments.
The changes I made were:
rearrange the on function
commented out the jQuery test via console.log() to stop errors from being thrown
prevent the default of the click event on the anchor element
switched the document.write to a $('body').append()
Hope that helps!
The problem in your fiddle was that somehow fiddle screwed up the whole document write thing.
You were close though. You can't attach an event listener to a node that's not there which you tried with $(node).on().
However, from the linked documentation you are supposed to use it like so:
$(document).on("click", "selector", fn);
I've updated your fiddle to use Zepto instead of jQuery and also set it to run on domReady which makes the ready event in your code unnecessary.
http://jsfiddle.net/zR2xL/3/

How do I clear the JQuery Mobile list search filter?

I have a JQuery Mobile (1.0rc1) application that has a list view with a search filter implemented. It's similar to this sample.
Under certain conditions, I am dynamically loading additional items into the list with an ajax call. When this happens I want to clear anything entered in the search filter, otherwise I end up with a partially filtered list.
I've tried firing the clear button like this:
$('.ui-button-clear', $.mobile.activePage).click();
and clearing the form like this:
$("form > input", $.mobile.activePage).val('');
but neither worked. Can someone enlighten me to the proper way to accomplish this?
You should be able to clear clear the searchfilter with
$('input[data-type="search"]').val("");
Edit: To update the list you will also have to trigger the "change"-event on the searchfilter:
$('input[data-type="search"]').trigger("keyup");
JSFiddle
if you talking about Jquery mobile listview, then you need this
$('#autocomplete li').click(function () {
$('.ui-input-clear').trigger("click");
});
I use the following code:
$("form")[0].reset();
The [0] points to the DOM element method.
Also see How to reset (clear) form through JavaScript?

Resources