Select2 - How to set default value for "infinite scroll" example? - jquery-select2

I'm opening a form for editing some record. I'm using an "infinite scroll select2".
I want the input to show the option already saved to that field (I'm editing a record...)
How can I do that? This way is not working:
$('#e7').select2('data', { id: 8, text: 'foo' });
I've created a jsfiddle to show that: http://jsfiddle.net/lucianocosta/Dyh8W/1/

ivaynberg answered me: https://github.com/ivaynberg/select2/issues/688#issuecomment-11971899
you have to pass in an object that is in the same format as what your renderers expect. in this case the renderer you specified expects the title attribute, not text. see here: http://jsfiddle.net/Dyh8W/2/
So the solution here is:
$('#e7').select2('data', { id: 8, title: 'foo' });

Related

Create Remote Select2 v4 Option with custom parameters

here is the problem, I can create the custom option as specify on documentation like this:
var option = new Option("my custom option", "myid", true, true);
$('select[name="myselect"]').append(option).trigger('change');
// manually trigger the `select2:select` event
$('select[name="myselect"]').trigger({
type: 'select2:select',
params: {
data: {
id: "myid",
text: "my custom option",
customparam: {
hello: "I'm here"
}
}
}
});
So, this creates the option normally and shows on select2 as selected as expected, this also trigger the select2:select event and I can read the extra parameter when this event is trigger, but here comes the problem, I can NOT access the extra parameter by doing this:
$('select[name="myselect"]').select2('data')[0].customparam
it's like the custom parameter is not attached to the element and it was only pass to the events.
for all who try to find an solution to add the custom parameters back on remote select2, here is what I did and worked perfectly:
$('select[name="yourfieldname"]')
.append(new Option(`${doc.n}`, doc._id, true, true))
.select2('data')[0].customparam = doc.i;
then just when you need call:
$('select[name="yourfieldname"]').select2('data')[0].customparam
The method described by #rafaelrglima's works for me, but I prefer the method below, which was gleaned from dejan9393's answer in Github issue 2830:
var dataAdapter = $('select[name="myselect"]').data('select2').dataAdapter;
dataAdapter.addOptions(dataAdapter.convertToOptions([{
id: "myid",
text: "mycustomoption",
customparam: "hello"
}]));
I prefer this way because I don't have to have one step for adding "id" and "text" and separate step for adding custom parameters. Also convertToOptions takes an array, so you have a convenient way to add multiple options in one step.

Angular reactive forms - How to set default value of select/dropdown control?

This week, i ran into a problem where dropdown control of angular material was not populating the default value coming from the API. My datasource looked like this:
public selectDataSource = [{
id: 1,
name: 'Option 1'
}, {
id: 2,
name: 'Option 2'
}, {
id: 3,
name: 'Option 3'
}];
Value was coming from the API as:
{
'selectedOption': {
id: 2,
name: 'Option 2'
}
}
But somehow, when i assigned the value to reactive form control field, it didn't get auto populated, which ideally should be the expected behavior.
Reason, answer below.... Go on
After all the research, I came to conclusion that Angular will only make a value as default selected if it points to the same memory location as in the original dataSource array.
In the example above, selectDataSource is stored in different memory location whereas the value coming from the API is pointing to different memory location.
Solution: Loop through the original datasource and filter the matched entry with result from API, to get the selected object from the original dataSource and that's it you are done. Something like below:
selectedOption = selectedDataSource.filter((option) => option.id === selectedOption.id)[0];
Now, we have selectedOption pointing to the same memory location from the original dataSource array.
Below is the link to solution. Try toggeling the variable solveProblem to see the default behaviour(when pointing to different memory loctaion).
https://stackblitz.com/edit/angular-reactive-dropdown-control
In a Hope, it'll help someone someday.
Thanks,
Manish Kumar
I had the same problem with dropdowns not showing already saved / selected choices and this answer to another question finally helped.
The solution is using the [compareWith]="compareFunction" property on the select tag to override the default comparison happening. By referencing a custom compare function you can tailor how the matching of initial value to dropdown values should work.
My current solution:
<mat-form-field>
<mat-select formControlName="gender" [compareWith]="compareSelectValues">
<mat-option *ngFor="let gender of genderValues" value="{{gender.id}}">{{gender.label}}</mat-option>
</mat-select>
</mat-form-field>
And Typescript function:
private compareSelectValues(selectedValue, compareValue): boolean {
return Number(selectedValue) === compareValue;
}
Number() is needed as the value is converted to a string after setting it in HTML. Using material design components here but looking at the other post, this shouldn't change the general functionality. Hope this helps someone, who finds this question before the other one, like I did.

jquery UI tooltip - use flat string for content not working

My problem is quite simple.
I want to use a flat sstring for the content function within the tooltip,
instead of using the value of title attributes.
But why mine code is not working?
$(function () {
$(document).tooltip({
content: "amsdmkam";
});
});
JSFiddle : http://jsfiddle.net/matildayipan/vdc6adwv/
If you want a flat string content instead of using the value of title attribute, you also must put title attribute in input tag
Another error is the semicolon after content: "amsdmkam".
Please check again with my edit
JSFiddle : http://jsfiddle.net/vdc6adwv/2/

Sitecore MVC and FieldRenderer.Render for Links

I'm trying to render a general link field like this - FieldRenderer.Render(item, "link").
This works as expected but how do I set custom text within the a tag that gets rendered. I want my output to look something like this
[custom text from another field]
Basically, the text for the link should come from another field on the item.
Thanks
Jason has a great idea, but this functionality is out of the box.
#Html.Sitecore().BeginField("Link Field", new { haschildren= true })
#Html.Sitecore().Field("Text Field")
#Html.Sitecore().EndField()
No need to modify anything at all.
You probably want to try the following:
#Html.Sitecore().BeginField("Link Field")
//custom code
#Html.Sitecore().EndField()
Varun's answer is definitely correct, however you will encounter an issue when the content editor has put a value into the Description field of a General Link. The link renderer will output both the description and whatever is between the BeginField and EndField methods.
A solution would be to allow for an extra parameter (HideDescription) which can hide the description. Two possible solutions for this would be;
Override the standard Sitecore.Xml.Xsl.LinkRenderer class with your own that would stop the description from being put in.
Add a custom pipeline step after the Sitecore.Pipelines.RenderField.GetLinkFieldValue which will do some post rendered processing to remove the description.
Option 2 is less invasive but is a little more difficult to make sure the results are 100%. Once you have this you can then render fields like the following;
#Html.Sitecore().BeginField("Link Field", new { HideDescription = true })
#Html.Sitecore().Field("Text Field")
#Html.Sitecore().EndField()
already has been answered but this worked for me
#Html.Sitecore().BeginField("Target URL", item.InnerItem, new { text = #Html.Sitecore().Field("Title", item.InnerItem) })
#Html.Sitecore().EndField()
You can also use begin and end-field and use the haschildren property, this will hide the text and just display any child-content between the begin and end statements:
#Html.Sitecore().BeginField("ItemName/ID", Model.DataSourceItem, new {
haschildren = true,
#class = "my-custom-class"
})
<span class="extra-content">
#Html.Sitecore().Field("Text Field")
</span>
#Html.Sitecore().EndField()

Select2 doesn't show selected value

Select2 loads all items from my list successful, the issue I found when try to select a specific value when page loads. Example:
:: put select2 in a specific html element, no value is selected even all items are loaded.
$('#my_id').select2();
:: When the page is loaded I'm trying to show a specific item selected, but doesn't work as expected, because even selected, the select2 doesn't show it.
$('#my_id').val('3'); //select the right option, but doesn't render it on page loads.
How to make a selected option to pop up when pages loads?
Thanks in advance.
#UPDATED
:: How I load all select2 items (sorry, its jade, not pure HTML):
label(for='category') Category
span.required *
select(id='category', style='width:230px', name='category')
option(value='') - Select -
each cat in categories
option(value='#{cat.id}') #{cat.description}
P.S.: All items from my list are loaded.
:: How I initialize the select2:
Just put the following line code on my javascript and it does successful:
$('#category').select2();
:: How I'm trying to select a specific value:
First attempt:
$('#category').select2(
{
initSelection: function(element, callback) {
callback($('#field-category').val());
}
}
);
Second attempt:
$('#category').val($('#field-category').val());
P.S.: #field-category has a value its a hidden input field and works OK.
You need to use the initSelection option to set the initial value.
If you are using a pre-defined select element to create the select2, you can use the following method
$('select').select2().select2('val','3')
Demo: Fiddle
add a trigger change after setting val:
$('#my_id').val('3').trigger('change');
A very simple way to tackle this problem is :
//Step1: Here assuming id of your selectbox is my_id, so this will add selected attribute to 1st option
$('#my_id option').eq(0).prop('selected',true);
//Step2: Now reinitialize your select box
//This will work, if you haven't initialized selectbox
$('#my_id').select2();
or
//This will work, if you have initialized selectbox earlier, so destroy it first and initialise it
$('#my_id').select2('destroy').select2();
This may help:
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
You can find more on details here:
Thanks
Per here initSelection is deprecated in Select2 4.0 and later.
Using Select2 4.0.0 this worked for me:
$('#my_id').select2({val:3});
HT: #Kokizzu
Here is how to make val in select2 just select the corresponding element.
For some reason, select2 doesn't provide the function to look up selections by id.
init:
$("#thing").select2({data:sources, initSelection: function(item, callback) {
// despite select2 having already read the whole sources list when you
// do .val(n) you have to explicitly tell it how to find that item again.
var to_be_selected = null;
$.each(sources, function(index, thing) {
if (thing.id == item.val()) {
to_be_selected = thing;
return;
}
})
callback(to_be_selected);
}})
normal code
// to load the thing with id==3 from the initial sources list.
$("#thing").select2({'val': 3})
For me I was sending selected in the data set still default option was not getting selected. I had to do something like below to make it work -
$(".select").select2({
data: data_names
});
data_names.forEach(function(name) {
if (name.selected) {
$(".select").select2('val', name.id);
}
});
I had a multiple select2 box with multiple selections.
Step 1 was to put my string of school_ids into an array of integers corresponding to the id of each school, and remove a leading zero. I had to do this in a separate script tag.
<script>
var school_ids = <%= raw JSON.parse(#search.school_ids).map{|x| x.to_i} - [0]%>
</script>
Step two was to create the select box, then set the values, then trigger like so:
<script>
$(document).ready(function() {
$('.select2-multiple').select2({
placeholder: "Hit Enter After Selection",
width: 'resolve'
});
$('.select2-multiple').val(school_ids);
$('.select2-multiple').trigger('change');
</script>
trigger just select2 to set the value
$('#my_id').val('3').trigger("change.select2");
and this will trigger select2 with dropdown
$('#my_id').val('3').trigger("change");
I meet with the same problem, this works for me:
Using Select2 > 4.0.0
$('#select_id').val('3').trigger('change');
var option=$(this);
if(option.val()==data.StudentCourses.CourseId)
{
option.setAttribute('Selected');
}
});
i have initilized select2 because i just want few options selected from them.
If you are using select2 v4.0.0 or above, you can check select2 documentation
// Initialize select2 for all select tags
$('select').select2();
// Initialize select2 for a specific id
$('#my-id').select2();
// Initialize select2 for a class
$('.my-class').select2();
// Update the displayed value after changing the selected option.
$('#my-id').trigger('change');
$('.classname').each(function() {
$(this).siblings().find('.select2selection__rendered').text($(this).text())
})
in my case I were dealing with a class then I used this way to set showing content at select2
<option selected value="your_value">your_text</option>
u need to put this at each select box's first option

Resources