Kendo dropdownliast select element containing a substring - javascript

I have a Kendo DropDownList what I have to select an element by the text containing 8. I can select element by the full string, I only need to select it by a substring.
The partly working code looks like:
var ddlist = $("#HibaTipusKod_" + munkatargyaId).data("kendoDropDownList");
console.log(ddlist);
ddlist.value("8/a");
ddlist.trigger("change");
My need is:
ddlist.value(*startswith/contains*"8");
ddlist.trigger("change");
At the logging I can see it right.

You could try this:
var options = ddlist.dataSource.options.data;
$.each(options, function(i, item) {
if (item.text.indexOf('8') !== -1) {
dropdownlist.select(i);
return false;
}
});
Demo
Bare in mind that using indexOf to search for the sub-string will be case sensitive, there are lots of alternative methods that could better suit your needs in this question.

Related

How to apply range of values to a partial attribute selector? [duplicate]

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.
I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?
EDIT: The attribute filters allow you to select based on patterns of an attribute value.
You can use the filter function to apply more complicated regex matching.
Here's an example which would just match the first three divs:
$('div')
.filter(function() {
return this.id.match(/abc+d/);
})
.html("Matched!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="abcd">Not matched</div>
<div id="abccd">Not matched</div>
<div id="abcccd">Not matched</div>
<div id="abd">Not matched</div>
James Padolsey created a wonderful filter that allows regex to be used for selection.
Say you have the following div:
<div class="asdf">
Padolsey's :regex filter can select it like so:
$("div:regex(class, .*sd.*)")
Also, check the official documentation on selectors.
UPDATE: : syntax Deprecation JQuery 3.0
Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:
jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
return function (elem) {
var matchParams = expression.split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels, '')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
});
These can be helpful.
If you're finding by Contains then it'll be like this
$("input[id*='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Starts With then it'll be like this
$("input[id^='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Ends With then it'll be like this
$("input[id$='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is not a given string
$("input[id!='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which name contains a given word, delimited by spaces
$("input[name~='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen
$("input[id|='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.
For example if your want to only select div with id starting with "abc", you can use:
$("div[id^='abc']")
A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/
var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);
Here you go!
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here:
http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx
$("input[name='option[colour]'] :checked ")
I'm just giving my real time example:
In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".
document.querySelectorAll("[id^='select2-qownerName_select-result']");
When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.
$("[id^='select2-qownerName_select-result']")
If you just want to select elements that contain given string then you can use following selector:
$(':contains("search string")')

How to get the first item in an array that doesn't match another array

I'm building a preference list where the user selects a number of items from a list and they're then presented back to them in order of preference.
I've a prototype built, but I need some help with a feature I'd like to add. I want the user to see what preference the next item they select will be.
The behaviour would be:
First the user is presented with "Choose your 1st preference"
When they select their 1st preference this then changes to "Choose your 2nd preference, and so on.
It'd also need to know if they'd deselected a preference and on doing so it'd need to say "Choose your 1st preference (or whatever preference)" again.
I've created a JSfiddle here
I'm imagining to be able to use grep in some way to do this?
var nextPreference = $.grep(preferencesAsText, function(v) {
// return v !== First preference that isn't one of the preferences that are already selected
});
Any help would be great, thanks!
Edit: I've managed to get an array of the items that are in the list of chosen preferences by doing this:
var chosenPreferences = $('[data-schemeorder]').map(function() {
return $( this ).text();
})
.get();
var arrayOfChosen = $.makeArray(chosenPreferences);
console.log(arrayOfChosen);
So basically I just need a way of finding the first preference that isn't in this list, if that makes sense... updated fiddle
Why don't you use schemePrefArray.length to get the number of elements selected and display the text you need?
the text displayed would be preferencesAsText[schemePrefArray.length]
no?
OK, so I think I've figured this one out. If you create an array of the chosen preferences and then use grep to create an array of the items that aren't in the preferences text, you can then use this to find the first item that is not selected.
var chosenPreferences = $('[data-schemeorder]').map(function() {
return $( this ).text();
})
.get();
var arrayOfChosen = $.makeArray(chosenPreferences);
var differenceArray = [],
initialVal = 0;
$.grep(preferencesAsText, function(el) {
if($.inArray(el, arrayOfChosen) == -1) differenceArray.push(el);
initialVal++;
})
if(differenceArray[0] === undefined) {
$('#chosenLimit').show();
$('#chooseYourPrefs').hide();
} else {
$('#chosenLimit').hide();
$('#chooseYourPrefs').show();
$('#chooseNextPreference').text(differenceArray[0]);
}
And an updated fiddle here

Remove option from selected list based of index?

I have two select lists and based off the selected index of either one I need to remove the option at that index from both lists.
I have seen example of doing this for the currently selected option using the remove() function but that would only work for one list as the other list might have a different option selected or none at all.
Knowing just the index value is it possible to do this with JavaScript / jQuery? I already have the code that figures out which list to pull the index from and get that index value. I just have not found a way to specify an index value for the removal.
Code developed based off comment:
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOptionIndex;
if (codeType == "Project")
{
selectedOptionIndex = $("#SelectedProjects :selected").index();
}
else
{
selectedOptionIndex = $("#SelectedTasks :selected").index();
}
alert(selectedOptionIndex);
selectedProjectsField.eq(selectedOptionIndex).remove();
selectedTasksField.eq(selectedOptionIndex).remove();
}
Using The :eq() Selector
You could use the :eq() selector to target a specific element by it's index and then call remove() to remove it from the DOM :
// Syntax Example: This will remove then (index)th option element
$('select option:eq(index)').remove();
So in your case, you would simply want to concatenate your selectedOptionIndex into the selector to target selector using one of the following :
// Remove a specific option of your SelectedProjects element
$('#SelectedProjects option:eq(' + selectedOptionIndex + ')').remove();
Example
You can see an interactive example here and demonstrated below :
This code should work:
$('#SelectedProjects option')[index].remove();
$('#SelectedTasks option')[index].remove();
or
selectedProjectsField.find('option')[selectedOptionIndex].remove();
selectedTasksField.find('option')[selectedOptionIndex].remove();

How should I create a listbox in a HTML form?

I would like to have a listbox where users can add items they have entered in a text input. The list should also have remove, edit functionality.
What's the best way to do this (i.e. hardcode or is there a jquery)? I am guessing would need javascript which is fine.
How would I read all the values from JS? I want to concatenate the items with a delimiter so that I can send it via ajax
Here's an example using jQuery adding all options from a listbox to a comma delimited string;
function toAllan() {
var allanString = "";
var allanOptions = $('.myListBox option');
allanOptions.each(function (index) {
allanString += $(this).val();
if (index != allanOptions.length - 1) {
allanString += ",";
}
});
return allanString;
}
EDIT I ran across this alternative which is much cleaner IMO.
function toAllan() {
return $('#myListBox option').map(function (index) {
return $(this).val();
}).get().join(',');
}
Here's a jsFiddle demonstrating this (also includes adding and removing of elements from the list box): http://jsfiddle.net/srGz7/4/
Probably you can take a look at this jquery plugin - jQuery Tokeninput. However you can't edit the item.

Extracting specific text from select option boxes

It's possible I'm just misusing .filter() here, but I've been trying to extract a particular piece of text from javascript option boxes without much success.
In short, each of my option boxes has a bunch of info, then, in brackets, ([x] items left in stock).
I'd like to extract that [x], but I can't seem to get any sort of regular expression filtering working in jQuery - or, perhaps, I'm doing it wrong.
In short, if anyone could complete the below, I'd be very appreciative:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
[ your code here]
});
Any help very appreciated.
Something along these lines:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
var n = selectedItem.match(/(\()(\d+)(\))/)[2];
});
Of course, this expression depends on the fact that your data is formatted as (number) string
This should get you what you need.
var pattern=/\[(\d+)\] items left in stock/;
var qty = pattern.exec(selectedItem)[1];
So you should use the JavaScript string.match function
var s = "[100] items left in stock";
var p = s.match(regexp);

Categories