"select2" Add constant option - jquery-select2

I am currently using Select2 in a project and would like to add a option to my select list that shows up regardless of what the user types or searches. The idea is to have a "Add new" option always present in the list.
I do not think my code is necessary here (but if needed I may provide) as the only thing i'm lacking knowledge in this specific topic is on how to keed the option always showing.
I thought of using the matcher attribute, but i'm not sure how.

I've managed to do it setting a new matcher, the problem was I was not sure on how to create a new matcher and still use the select2 default one.
Something else I was missing was the full version of select2.
function newMatcher(term, text){
//The "ADD NEW" String is the text in the option I want to always show up.
//The code after OR looks for the actual results for the user's search
if ((text.toUpperCase().indexOf("ADD NEW") > -1)
|| (text.toUpperCase().indexOf(term.toUpperCase()) > -1)) {
return true;
}
}
$(document).ready(function() {
$.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
$('select').select2({
matcher: oldMatcher(newMatcher)
})
})
});

Related

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()

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

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

onChange event for custom select menu jquery mobile [duplicate]

I have a set of dynamically generated dropdown boxes on my page. basically I clone them using jQuery. now I want to capture the value selected on each dropdown on change event.
I tried something like this which did not work.
$('._someDropDown').live('change', function(e) {
//debugger;
var v = $(this);
alert($(this + ':selected').val());
alert($(this).val());
});
How do I get it done?
To get the text of the selected option
$("#your_select :selected").text();
To get the value of the selected option
$("#your_select").val();
This is what you need :)
$('._someDropDown').live('change', function(e) {
console.log(e.target.options[e.target.selectedIndex].text);
});
For new jQuery use on
$(document).on('change', '._someDropDown', function(e) {
console.log(this.options[e.target.selectedIndex].text);
});
$("#citiesList").change(function() {
alert($("#citiesList option:selected").text());
alert($("#citiesList option:selected").val());
});
citiesList is id of select tag
Check it Out-->
For getting text
$("#selme").change(function(){
$(this[this.selectedIndex]).text();
});
For getting value
$("#selme").change(function(){
$(this[this.selectedIndex]).val();
});
You can try:
$("._someDropDown").val();
To get the value of a drop-down (select) element, just use val().
$('._someDropDown').live('change', function(e) {
alert($(this).val());
});
If you want to the text of the selected option, using this:
$('._someDropDown').live('change', function(e) {
alert($('[value=' + $(this).val() + ']', this).text());
});
try this...
$("#yourdropdownid option:selected").val();
This is actually more efficient and has better readability in my opinion if you want to access your select with this or another variable
$('#select').find('option:selected')
In fact if I remember correctly phpStorm will attempt to auto correct the other method.
In case you want the index of the current selected value.
$selIndex = $("select#myselectid").prop('selectedIndex'));
The options discussed above won't work because they are not part of the CSS specification (it is jQuery extension). Having spent 2-3 days digging around for information, I found that the only way to select the Text of the selected option from the drop down is:
{ $("select", id:"Some_ID").find("option[selected='selected']")}
Refer to additional notes below:
Because :selected is a jQuery extension and not part of the CSS specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :selected to select elements, first select the elements using a pure CSS selector, then use .filter(":selected"). (copied from: http://api.jquery.com/selected-selector/)
You can also use :checked
$("#myselect option:checked").val(); //to get value
or as said in other answers simply
$("#myselect").val(); //to get value
and
$("#myselect option:checked").text(); //to get text

JQuery UI Multiselect how to get selected options values

wasted my day while searching how to get selected options values in JQuery UI widget by Michael Aufreiter. Here's the link to his demo site and github: http://quasipartikel.at/multiselect/
As a result I just need value fields of selected options without POST/GET sendings to PHP script.
I tried many methods and resultless.
Need your help and ideas
*Found many topics about jquery ui multiselect but useless because of Aufreiter :s *
That should work. Tested with Chrome console
$("#countries").val();
I went to the site you've got listed above, and was able to run this in my chrome console:
$('.ui-multiselect .selected li').each(function(idx,el){ console.log(el.title); });
It seems like the values you want are stored in the title attributes of the list items within the div.selected element.
Edit:
Doh! Well of course you want the values. Sorry mate. Completely missed that. The real goods are stored in the jQuery data() objects. In this case, the key you want is 'optionLink'. It maintains a reference to an option element. Each list item in the '.selected' div used the jQuery.data() method to add the underlying option to it.
So, you need to get the selected list items, iterate through, grab the 'optionLink' from the data jQuery data store, and then get the value.
The following code works on the example page:
$('.ui-multiselect .selected li').each(function(idx,el){
console.log(el);
var link = $(el).data('optionLink');
// link now points to a jQuery wrapped <option> tag
// I do a test on link first. not sure why, but one of them was undefined.
// however, I got all four values. So I'm not sure what the first <li>
// is. I'm thinking it's the header...
if(link){
// here's your value. add it to an array, or whatever you need to do.
console.log(link.val());
}
});
This is the first I've seen of the multiselect. It's slick. But I sympathize with your frustration trying to get something out. A 'getSelectedOptions()' method would be nice.
Cheers
Try accessing the selected values on the close event.
e.g.
$("#dropdown").multiselect({
header: false,
selectedList : 1,
height: "auto",
}).multiselectfilter().bind("multiselectclose", function(event, ui) {
var value = $("#dropdown").val();
});
Hope that helps.
Best solution
$('#select').multiselect({
selectAllValue: 'multiselect-all',
enableCaseInsensitiveFiltering: true,
enableFiltering: true,
height: "auto",
close: function() {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function(index, item) {
values.push($(item).val());
});
$("input[id*=SelectedValues]").val(values.join(","));
}
});
You can try this:
$('#ListBoxId').multiselect({
isOpen: true,
keepOpen: true,
filter: true
});

Resources