case sensitive in select2.js dropdown list - javascript

I am currently using select2.js 4.0.3
Scenario
let's say the dropdown list has these options
JavaScript
javascript
Javascript
javaScript
so... when user types java as of now... the list shows all the options (because case doesn't matter as of now)
Example 1
What I want to is... when user types Java only these options should show up
JavaScript
Javascript
Example 2
If user types script ... these options should show up
javascript
Javascript
Example 3
for aS
JavaScript
javaScript

I was looking for the same issue for a long time, but everywhere I found the opposite questions (how to make select2 case-insensitive), so I was very surprised when I found already working solution in the documentation.
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (data.text.indexOf(params.term) > -1) {
var modifiedData = $.extend({}, data, true);
return modifiedData;
}
return null;
}
$(document).ready(function () {
$("select").select2({
tags: true,
matcher: matchCustom
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
<select>
<option>javascript</option>
<option>Javascript</option>
<option>JavaScript</option>
<option>javaScript</option>
</select>

Related

What is the best way to populate select with large json file in terms of speed

I am trying to populate select list with relatively large local json data.
Is this the best way of doing this in terms of speed?
And also when trying to append the options into the select in another way ( the commented out lines ) the code is not working at all - can someone explain to me why is that?
$(document).ready(function() {
Sickness();
});
function Sickness() {
let sickness;
$.getJSON('https://next.json-generator.com/api/json/get/V1mWAT69Y').done(function(data) {
sickness = data;
$('#sickness').html('');
let sicknessOptions = '';
$.each(data, function(index, object) {
$('#sickness').append(`<option value="${object.value}">${object.text}</option>`);
// sicknessOptions += $(`<option value="${object.value.toUpperCase()}">${object.text.toUpperCase()}</option>`);
});
// $('#sickness').append(sicknessOptions);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sickness"></select>

add-from-autocomplete-only = "false" with auto-complete in ngInputTag Control not working

After spending a lot of time in investigating to resolve the issue to allow any tag along with autocomplete feature in ngInputTag. I end up with no results.
The issue is when I type the text which is in autocomplete list the tags get added successfully but when point comes to add the tags which is not in the tag list it accepting the first tag but when I enter second tag which is not in autocomplete list it makes the text color Red and not accepting the tag input.
To resolve the issue I have used on-tag-added but it did not worked. Same issue has been reported on Git-Hub Issue Link
Below is my code:
HTML
<tags-input ng-model="model" display-property="Name" key-property="Key"
placeholder="Enter Tags" add-from-autocomplete-only="false"
allow-leftover-text="true">
<auto-complete source="loadTags($query)"
highlight-matched-text="true"
select-first-match="true">
</auto-complete>
</tags-input>
Controller JS Code:
$scope.model = [];
$scope.loadTags = function (query) {
var deferred = $q.defer();
$http.get(ApiUrls.GetTagsByQuery + (query != null ? ("?query=" + query) : ""))
.then(function (result) {
if (result.data == null) {
result = [];
}
deferred.resolve(result.data);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
Any Help will be Highly Appreciated. Thanks.
Same problem !!! But if you remove key-property then it will works.
key-property is only for duplicate issue

Using initSelection in select2 3.5.2 for custom filtering

I have a text field which uses select2. Here is the initialization:
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0;
}).length===0)
{return {id:term, text:term};}
},
initSelection : function (element, callback) {
var data = {id: element.val(), text: element.val()};
callback(data);
},
tags:[],
tokenSeparators: [","],
data: [...data goes here...]
});
In this field, the user is supposed to put in a number, or select items from a list. If an item that the user puts in doesn't appear on the list, it ought be created as a simple tag (id and text identical). This works.
What doesn't work is when I set the value programmatically:
myvar.find('.placeholder lorem-ipsum').val(number).trigger("change");
The way it works now, is that when I set it to any value, it takes it without complaint, making a new simple tag. However, if I were to remove the initSelection parameter completely, it would ignore unknown values, and use known values as taken from the list (where tags are complex - id and text are different).
How do I make it so that if the value I set to the field is found on the list, it will use the item, and otherwise make a simple tag? The way it works now (simple tags only) is sort-of acceptable, but I'd prefer it worked ideally.
EDIT:
I've made examples for how it works with and without the initSelection parameter.
http://jppk.byethost12.com/with.html
http://jppk.byethost12.com/without.html
In short, I want it to work like with.html when I push "Add New Item" and I want it to work like without.html when I push "Add Existing Item".
Here is my best interpretation of what you want.
JSFiddle
The trick is to append the element to the select field.
var array = ['foo', 'bar', 'baz']
$.each(array, function(key, value) {
appendSelect(value);
});
$("#foo").select2();
$('#submit').click(function() {
var val = $('#name').val();
$('#name').val('');
array.push(val);
appendSelect(val);
});
function appendSelect(value) {
$('#foo').append($("<option></option>").text(value));
}
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.1/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.1/js/select2.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<div class='container'>
<select id='foo' multiple="multiple" class='form-control'></select>
<label>Input</label>
<input id='name' />
<button id='submit'>submit</button>
</div>
Much, much later, I found a solution that works right:
initSelection : function (element, callback) {
var eArr = element.val().split(",");
var data = [];
for (var i=0;i<eArr.length;i++) {
for (var j=0;j<preExistingData.length;j++) {
if (preExistingData[j]["id"] === eArr[i]) {
data.push(preExistingData[j]);
continue;
}
}
data.push({id: eArr[i], text: eArr[i]});
}
callback(data);
},
This not only checks if the value is among the pre-existing values (in which case it uses that item), but also if the value is a comma-separated list of values (in which case it properly encapsulates them as JS objects).

use jquery variable in # block razor

I'm strugling with a jquery script inside a cshtml page. For short my question is how to use a var inside a # statement in a cshtml page?
below an example of what I'm trying:
<select id="DefaultText">
<option value="-1">-- select --</option>
#foreach( var d in Model.DefaultTexts )
{
<option value="#d.Id" >#d.Name</option>
}
</select>
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
var text = #Model.DefaultTexts.First( t => t.Id == id );
$('#CustomProductText').val(text);
});
</script>
I can't reach the var id. It's out of scope. I've also tryed it with a for loop and a if statement. But in the if statement I get the same error: out of scope.
The full story is this:
On my page I've a dropdown list. The items to select are short names for default text parts. Based on the id or name, I want to show the default text part in a textbox.
#CustomProductText is my textbox where the content should be placed (code not posted).
I've also tryed it with #: and statement but that did not work.
What am I doing wrong or maybe its not even possible what I'm trying to do.
As an alternative I've added a action to my controller to get the text form there. Below the code:
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
$.post("Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
//$('#CustomProductText').val(text);
});
</script>
controller code:
[HttpPost]
public ActionResult GetDefaultText(int id)
{
using( var context = new MyContext() )
{
var text = context.DefaultText.First( d => d.Id == id ).Text;
return this.Content( text );
}
}
This doesn't work. The action doesn't get hit in debug mode.
regards,
Daniel
The $.post that is not working for you, you should prefix the url with / sign and it will be hit as expected:
$.post("/Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
As for the razor solution, you can't use javascript variables in the razor code as it's not a scripting language. What razor does is simply rendering the strings (be it html or javascript or anything) into the page.
To do what you want you either need to request the server to pass the text to your page or render all the texts you have in the page and then access this rendered content in your javascript.

Mixing JavaScript and Scala in a Play template

I'm not sure how this is done. I could hard code the route I'm trying to use, but I'd like to do this the right way.
I have a dropdown that needs to load a new page on change. Here's basically how I'm trying to do it (I've tried a few variations of this):
#getRoute(value: String) = #{
routes.Accounts.transactions(Long.valueOf(value))
}
<script type="text/javascript">
$(function() {
$("select[name='product']").change(function() {
location.href = #getRoute($(this).val());
}).focus();
$('a.view.summary').attr('href', "#routes.Accounts.index()" + "?selectedAccountKey=" + $('select[name=product]').val());
});
</script>
This produces a identifier expected but 'val' found exception. I also tried surrounding it in quotes, but that causes a [NumberFormatException: For input string: "$(this).val()"]
So how the heck do I insert a value from JavaScript into a Scala function?
Edit
Here's my solution, inspired by the accepted answer. This dropdown is defined in a tag that's made for reuse by different components, and the base URL is different for each component. The way to achieve this was to pass a function that generates a URL based on an account key into the dropdown:
#(accountList: List[models.MemberAccount],
selectedAccountKey: Long,
urlGenerator: (Long) => Html
)
<select name="product">
#for(account <- accountList) {
#if(account.accountKey == selectedAccountKey) {
<option selected="selected" value="#urlGenerator(account.accountKey)">#account.description (#account.startDate)</option>
} else {
<option value="#urlGenerator(account.accountKey)">#account.description (#account.startDate)</option>
}
}
</select>
<script type="text/javascript">
$(function() {
$('select[name=product]').change(function() {
location.href = $(this).val();
});
});
</script>
Then you can define a function like this to pass in:
#transactionsUrl(memberAccountKey: Long) = {
#routes.Accounts.transactions(memberAccountKey)
}
#accountsDropdown(transactionDetails.getMemberAccounts(), transactionDetails.getMemberAccountKey(), transactionsUrl)
You need a way of storing all URLs in the page, e.g.
<option value="#routes.Accounts.transactions(id)">Display</option>
Then onChange, you can:
$("select[name='product']").change(function() {
location.href = $(this).val();
});

Categories