Get items from Select2 after data has been loaded - javascript

I'm trying to force the open method and select item with select2 like this.
$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
items = e.items.results;
if (items.length == 1) {
$(this).val(items[0].text);
}
});
$(".select").select2('close');
But I cannot get inside the select2-loaded evaluation and the close is happening also to quick. I want to select the first element by default if there is only one element on the list.
When the 'open' occurs, it automatically performs the mechanism to get and load all the elements in my list. If I comment the close method it will take some milliseconds to display the elements on the list.
But what I want is to refresh my list (this is done by the open) then I want to select only if there one element and the close my list ('select')
How can I achieve this? This behaviour will be trigger by a onchange event of another list. (nested selects)

You should move the close call INSIDE the select2-loaded event, so it'll only close the select element after it selected the item. Otherwise you're opening, setting event for future event, then closing immediately.
$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
items = e.items.results;
if (items.length == 1) {
$(this).val(items[0].text);
$(".select").select2('close');
}
});

Related

how can I check if a particular item is clicked with .blur() in jquery

I have an autocomplete dropdown that appears when a user starts typing in a textbox (I'm using jquery mobile but I don't think that's important to my problem). I want to be able to hide the whole dropdown list when a user clicks anywhere on the page. However, I don't want to hide the dropdown when a user actually clicks on the dropdown itself.
Is there a way I could catch the click event in order to know what was clicked?
Here's my blur function:
//hide autocomplete when dropdown is not clicked
$("#search-div input").blur(function () {
$("#autocomplete-list").hide();
});
I was thinking of somehow putting an if statement in my blur function. Here's my pseudo code:
if( dropdown clicked)
{
run code to take text from dropdown and place in textbox
}
else
{
hide dropdown
}
Would it be possible to know whether my dropdown is clicked or something else is clicked while in my blur function? When I debug my javascript I'm only seeing an event that's related to the textbox doing the blur()
Edit:
Here is a function I'm using to handle when the dropdown is clicked:
$( document).on( "click", "#autocomplete-list li", function() {
var selectedItem = event.target.innerHTML;
$(this).parent().parent().find('input').val(selectedItem);
$('#autocomplete-list').hide();
runSearchQuery();
});
You can listen for any click, not just a blur, and then check what the clicked element was. e.currentTarget gives you what was clicked.
var clickHandler = function(e) {
if ($(e.currentTarget).hasClass('dropdown')) {
// do nothing
} else {
// Make sure you unregister your event every
// time the dropdown is hidden.
$(window).off('click', clickHandler);
// hide
}
}
// When the dropdown comes down, register an event on the whole page.
$(window).on('click', clickHandler);

Can't detect Select/Dropdown List Select event on load

Whenever user selects something from a dropdown menu I want to catch the selected item and do something:
$("#user-list").live("change", function() {
var selecteduser = $(this).find(":selected").text();
....do something with the selected user
});
Great! This works!
However, sometimes I want to load the page with one of the items already pre-selected as pre-selected list item is passed in as a part of the model:
#model RoleUsers
#Html.DropDownListFor(model => model.SelecteUserId, Model.Users)
The Change event doesn't trigger then unfortunately.
I have a feeling there is a different event out there that I'm missing...
How can I activate my action when a list item is selected on page load, not by a user ?
Thank you.
On document ready, just trigger change()
$(function() { $("#user-list").change(); });
PS, live() is deprecated, consider using on()

How to set the focus on a javascript modal window?

Our website involves some javascript that produces overlay modal windows.
There is one accessibility problem with this though, once the modal is triggered, the focus is still on the trigger element and not on the modal itself.
These modals can include all sorts of html elements, headings, paragraphs and form controls. What I would like is the focus to begin on the first element within the modal, so most likely to be a h4 tag.
I have explored using the focus() function however this does not work with a number of html elements.
One thought was to add an empty a tag in the window which could gain the focus, but I am unsure about this method.
very late to the party, but the existing answers do not respect accessibility.
The W3C wiki page on accessible modals offers more insight than what's asked in the OP, the relevant part is having tabindex=-1 on the modal container (which should also have an aria-dialog attribute) so it can get :focus.
This is the most accessible way of setting the focus on the modal, there is also more documentation about keeping it in the modal only - and returning it to the element that triggered the modal - quite a lot to be explained here, so I suggest anyone interested to check the link above.
You can append textbox to the beginning of the modal HTML, set focus then hide the textbox. Should have the desired effect as far as I understand your needs.
You could try to blur() the element that has the focus.
to trap focus inside the modal I have used this approach. So the basic idea behind it is exactly to trap the focus in the modal HTML elements and not allowing it to go out of the modal.
// add all the elements inside modal which you want to make focusable
const focusableElements =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const modal = document.querySelector('#exampleModal'); // select the modal by it's id
const firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal
const focusableContent = modal.querySelectorAll(focusableElements);
const lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal
document.addEventListener('keydown', function(e) {
let isTabPressed = e.key === 'Tab' || e.keyCode === 9;
if (!isTabPressed) {
return;
}
if (e.shiftKey) { // if shift key pressed for shift + tab combination
if (document.activeElement === firstFocusableElement) {
lastFocusableElement.focus(); // add focus for the last focusable element
e.preventDefault();
}
} else { // if tab key is pressed
if (document.activeElement === lastFocusableElement) { // if focused has reached to last focusable element then focus first focusable element after pressing tab
firstFocusableElement.focus(); // add focus for the first focusable element
e.preventDefault();
}
}
});
firstFocusableElement.focus();
you can find it here trap focus inside the modal

Handling HTML SELECT Options with event delegation to javascript on iPhone Safari

We are developing a web application with GUI customized to use on iPhone. A page on the app has 3 subsequent SELECT dropdowns, where selection of an option from 1st dropdown derives the options for 2nd dropdown, and so forth. The subsequent dropdown options are populated by javascript based on onchange event on previous dropdown.
The problem is that, on iPhone the options for a SELECT appears with 'prev' and 'next' links to move to previous and next control. When the 'next' link is clicked, then the control moves to next SELECT and displays the options. The javascript is triggered by onchange event for previous SELECT and populates the options for next SELECT. But on dropdown for 2nd SELECT displays the previous options before it is repopulated by the javascript.
Is there a workaround or event that can sequence execution of javascript and then selection of next control? Is there any event that can be triggered when a SELECT option is selected and before control leaves the SELECT element? Is there a handle for Next and Previous links for SELECT dropdown option display?
Maybe you could use the focus event, in jQuery this would be:
$('#select2').focus(function () {
// update select2's elements
});
Although the real question is when the iPhone overload comes in, and when the event get fired. And also can the select options be changed whilst in this view.
I had the same problem on my site. I was able to fix it by manually polling the selectedIndex property on the select control. That way it fires as soon as you "check" the item in the list. Here's a jQuery plugin I wrote to do this:
$.fn.quickChange = function(handler) {
return this.each(function() {
var self = this;
self.qcindex = self.selectedIndex;
var interval;
function handleChange() {
if (self.selectedIndex != self.qcindex) {
self.qcindex = self.selectedIndex;
handler.apply(self);
}
}
$(self).focus(function() {
interval = setInterval(handleChange, 100);
}).blur(function() { window.clearInterval(interval); })
.change(handleChange); //also wire the change event in case the interval technique isn't supported (chrome on android)
});
};
You use it just like you would use the "change" event. For instance:
$("#mySelect1").quickChange(function() {
var currVal = $(this).val();
//populate mySelect2
});
Edit: Android does not focus the select when you tap it to select a new value, but it also does not have the same problem that iphone does. So fix it by also wiring the old change event.

xul : creating a right click context menu item for only hyperlinks

I got a question to ask on building firefox plugin, basically my aim is to do following things,
1) In my plugin I want to show right click context menu item for only links[anchor tags] and hide the menu item for rest of the page
2) How to add dynamic list to my menu, i.e., adding the number of menu list items dynamically depending upon user's choice.
Can someOne point me to a right direction
Thanks !!
Bind an event listener for the contextmenu event and check whether the clicked element is a link, e.g.:
window.addEventListener("contextmenu", function(e) {
var menu = document.getElementById('your-menu-id');
if(e.target.nodeName == 'A') {
menu.hidden = false;
}
else {
menu.hidden = true;
}
}, false);
Read more about event properties and the menu element properties.
Have a look at the menu element's appendItem method.

Categories

Resources