select2 multiple - not setting values - jquery-select2

I use select2 v. 4.0.3 with angular2 and unable to pre-select values programmatically using multiple mode.
Based on previous answers, tried all these without luck:
let m = this.preview.mutagList.map(function (i) { return i['id']; });
console.log(m); // array of strings, which are the IDs for the options
$(".mutag").val(m);
$(".mutag").select2('val', m);
$(".mutag").select2({}).select2('val', m);
$(".mutag").select2({}).select2('data', this.preview.mutagList);
This is the select:
<select name="mutag" id="mutag" multiple data-placeholder="xxx" class="select2 form-control" dir="rtl" >
<option *ngFor="let c of mutagList" value="{{c.id}}">{{c.text}}</option>
</select>
Setting val() approach works for me in select2 with no multiple.
Please help!

Related

Removing selected option in multiple select2 clears all options

Using Laravel livewire, bootstrap 5 modal and select 2.
Select2 (s2) without multiple works fine. It's populated, selections save to the component, clearing is also fine.
When an s2 has multiple attribute, removing a selected option clears all the options and nothing is displayed in the results drop down. When adding a selection, this doesn't happen.
If I do a dispatchBrowserEvent and re-init the s2 it does work again.
My question is why does removing an s2 option require a re-init but an add doesn't.
Seems to be something to do with the rendering in render().
Some code...
Blade:
<div wire:ignore>
<select id="selectedTrades" wire:model.defer="selectedTrades" class="select-2" multiple="multiple" data-field="selectedTrades" data-allow-clear="false">
#foreach ($contractor_trades as $trade)
<option value="{{ $trade['id'] }}">{{ $trade['name'] }}</option>
#endforeach
</div>
Standard stuff. wire.ignore around the s2. The modal has wire:ignore.self.
JS:
$('.select-2').on('change', function (e)
{
var $this = $(this);
livewire.emit('setSelect2Property', $this.attr('data-field'), $this.val());
});
Component:
public function setSelect2Property($property, $value)
{
$this->$property = $value;
}
Just sets $this->selectedTrades to the array sent.
Adding:
The drop down has the options as expected.
Removing:
The thin light line under it is the container for the results that's now empty. The original select element does still have its options.
If I remove the livewire.emit from the js to test, the s2 behaves correctly.
I think it has to do with the components render method. I can't figure out what is happening different when I add versus remove.
I got this to work. The problem was the dropdownParent element I was using. I had it set to the modal. Setting it to the immediate parent element and it worked as expected.

How to select and add a new item in select2

I am pulling my hair off trying to do a very simple thing with select 2. When I edit a record of table1, I have a simple select dropdown with a list of items built from a field of table1 (with distinct). Sometimes I need to add a new item. So I thought that the example to create and add a new item would work but it does not. When I type the new item in the open box on top of the dropdown, I got "No result found"... ok but how do I force this new item to be selected and recorded in the database (and obviously available for later use)?
I am not really good in JS, so I presume I am doing something wrong or something is missing... please help.
<select class="selectAdd-who" name="who">
<option value="item1">item1</option>
<option value="item2" selected>item2</option>
<option value="item3">item3</option>
</select>
<script>
$(document).ready(function() {
$('.selectAdd-who').select2();
// Set the value, creating a new option if necessary
if ($('.selectAdd-who').find("option[value='" + data.id + "']").length) {
$('.selectAdd-who').val(data.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data.text, data.id, true, true);
// Append it to the select
$('.selectAdd-who').append(newOption).trigger('change');
}
});
</script>

How to get selected option in change callback of AngularDart component

I want to use a select HTML element to filter items in a table. For that I have a model value selectedCategoryId and event callback onFilterCategory for the change event. But when callback gets called the value selectedCategoryId is null.
I have the following HTML snippet:
<select id="category"
class="form-control"
[(ngModel)]="selectedCategoryId"
(change)="onFilterCategory()">
<option *ngFor="let category of categories"
value="{{category.id}}">
{{category.name}}
</option>
</select>
And the following dart snippet:
void onFilterCategory() {
print('onFilterCategory');
print('this.selectedCategoryId: ' + this.selectedCategoryId);
}
Do I need to use another callback?
ngModelChange is the event and $event the value
(ngModelChange)="onFilterCategory($event)"
with
void onFilterCategory(String value) {
Because you have 2-way binding
[(ngModel)]="selectedCategoryId"
you can also use
(ngModelChange)="onFilterCategory()"
with the onFilterCategory() as it is in your question.
The change event doesn't work because it fires too early - before [(ngModel)]="selectedCategoryId" was able to update selectedCategoryId.

Jquery Mobile Select does not reset

I am writing a web shop with Jquery Mobile where I want to use a select menu to browse the categories available. When the user selects a category I want to navigate to the same page but with a couple of parameters added to the url. This is my markup for the select:
<asp:Repeater id="productCatSelect" runat="server">
<HeaderTemplate>
<select id="productCatSelectMenu" data-native-menu="false" onchange="categoryClick();" class="button" data-theme="a">
<option data-placeholder="true">All Categories</option>
</HeaderTemplate>
<ItemTemplate>
<option value="<%# Eval("NodeID") %>" ><%# Eval("Description")%></option>
</ItemTemplate>
<FooterTemplate>
</select>
</FooterTemplate>
</asp:Repeater>
And here is the javascript:
function categoryClick() {
var mySelect = $("#productCatSelectMenu");
if (mySelect.val() != '') {
if (mySelect.val() == 0) {
$.mobile.changePage("shop.aspx", {reloadPage: true, transition:"slide"});
} else {
$.mobile.changePage("shop.aspx?c=" + $("#productCatSelectMenu").val() + "&n=" + $('#productCatSelectMenu :selected').text(), {reloadPage: true, transition:"slide"});
}
}
}
My problem occurs when I have navigated once and try to choose another option from the select, my javascript still retreives the previous value; the select does not seem to reset! However, when I press F5 and reload the page manually the menu works again, until I have used it once of course.
Anyone have any ideas on how I can fix this? As you can see in the javascript the "reloadPage: true" attribute does not fix the problem.
If you're using jQuery Mobile's custom select field, try
$("#select_id").selectmenu('refresh', true)
This will successfully reset the select options rendered by jQuery mobile.
You're going to need to reset this yourself, maybe try:
$('select#productCatSelectMenu option').attr('selected', false);
or
$('select#productCatSelectMenu option').removeAttr('selected');
or
$('select#productCatSelectMenu').children('option').removeAttr('selected').filter(':nth-child(1)').attr('selected', true);
or
$('select#productCatSelectMenu').attr('selectedIndex', -1);
I had a similar problem the other day
Reset/Un-select Select Option
I have no clue why Jquery mobile select is working the way it is. None of the above worked for me except for what is mentioned here. I am using the current versions
jquery-1.10.2.min.js
jquery.mobile-1.4.2.min.js
https://forum.jquery.com/topic/resetting-select-menu
var myselect = $("select#useOfColor");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
Have you tried $('#productCatSelectMenu').selectmenu('refresh');?
You can check information about the refresh method in the documentation

show text field on select other from drop down :ROR

How I should do this using javascript? I looked other places but every example uses Jquery.
Only on select other textbox should visible.
Assuming that you are on an older version of rails which has prototype as the js library.
in the onchange event of the select list add the javascript function to show the div containing the text box (let's say you show the text box for value 5 of the select list):
<select id="select_item" name="select_item" onchange="display_date_range(this);">
... where 5 is the value of the option that needs to show text box
</select>
function display_date_range(list) {
if(list.options[list.selectedIndex].value == 5) {
$("text_div").show();
}
else {
$("text_div").hide();
}
}
<div id="text_div"><input type="text" value="Hooraaahhh..." /></div>

Resources