Placeholder when using minimum length - tom-select

I'm using the shouldLoad functionality to set a minimum length of characters before data loads from a remote source, like the example here
shouldLoad:function(query){
if ( query.length < 3 ) return false;
return true;
},
Is there a way to show the user that they must then enter this minimum number of characters, like select2 does?
Thanks

Of course,
You can use not_loading in your renderer function which is triggered when you return false from shouldLoad.
Example:
render: {
option: function(item, escape) {
return `<div>${ escape(item.name) }</div>`;
},
item: function(item, escape) {
return `<div>${ escape(item.name) }</div>`;
},
not_loading:function(data,escape){
return `<div>Please enter 2 or more characters </div>`;
},
},
});
You can learn more from their official doc.
Hope it helps.

Related

Vuex state updated but input value does not when using v-model

I'd like to slice input value when the value is longer than limit length.
Of course I know there's maxlength property in input field, but I want show alert popup when the length exceeds the limit. When I set maxlength as I want the user to type, the popup-showing function was not called.
<template>
<input type="text" v-model="title">
</template>
<script>
export default {
data() {
return { MAX_LENGTH: 10 };
},
computed: {
title: {
get() { return this.$store.getters.title; },
set(title) {
if (title.length > this.MAX_LENGTH) {
alert('Too long!!');
// This part doesn't work as I wanted
this.$store.commit('updateTitle', title.slice(0, this.MAX_LENGTH);
} else {
this.$store.commit('updateTitle', title);
}
}
}
}
}
</script>
All the other parts work, but when the length of title exceeds 10, the state is updated while input field is not changed.
I found a solution.
Why title is not updated is, when I slice the string, anyway title remains as it is.
vm.$forceUpdate works in this case.

AngularJS: Move to next form input element after successful validation

I have written a custom directive for validation of my form fields. When certain criteria are met (i.e. it is dirty and valid), I want to set the focus automatically to the next input element. This is a requirement from my users, such that they can move through the forms most efficiently.
The simplified directive looks like this:
directive('custom', ['$parse', function($parse) {
return {
restrict: 'A',
require: ['ngModel', '^ngController'],
link: function(scope, element, attrs, ctrls) {
var model=ctrls[0], form=ctrls[1];
scope.next = function(){
return model.$valid
}
scope.$watch(scope.next, function(newValue, oldValue){
if (newValue && model.$dirty){
???
}
})
Now my question is: how can I identify
- the next input element (which is the next sibling) or possibly via the tabindex
- and focus on it
without using Jquery?
For me, it is currently not clear, how to get to the next input element from the available "scope" or "element" attributes without Jquery; and JQlite does nothave a "focus" method. Basically, I need a working substitute for ??? in my code.
Any help is highly appreciated. Thanks
Juergen
You can use [0] to get the underlying input element (which has a focus() function) from the angular/jqLite object (which doesn't).
app.directive('custom', ['$parse', function($parse) {
return {
restrict: 'A',
require: ['ngModel'],
link: function(scope, element, attrs, ctrls) {
var model=ctrls[0], form=ctrls[1];
scope.next = function(){
return model.$valid;
}
scope.$watch(scope.next, function(newValue, oldValue){
if (newValue && model.$dirty)
{
var nextinput = element.next('input');
if (nextinput.length === 1)
{
nextinput[0].focus();
}
}
})
}
}
}])
http://jsfiddle.net/Y2XLA/
element.next().focus() might not work if you have a complex form and input are nested into different divs.
I ended writing this directive (here I move the focus on Enter, but can be adapted to whatever event):
.directive('enterToTab', function($timeout) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var procAttr = 'data-ett-processed';
$timeout(function() { // Use $timeout to run the directive when the DOM is fully rendered
var formElements = element[0].querySelectorAll('input:not([' + procAttr + '="true"]), select:not([' + procAttr + '="true"]), textarea:not([' + procAttr + '="true"])');
// Run through all elements in form
var formElementsLength = formElements.length;
for (var i = 0; i < formElementsLength; i++) { // Add tabindex attribute
formElements[i].setAttribute('tabindex', i + 1);
// Go to next element on Enter key press
formElements[i].addEventListener('keypress', function(event) {
if (event.keyCode === 13) { // Enter
// Prevent Angular from validating all the fields and submitting
if (event.target.tagName !== 'TEXTAREA') { // Not on textarea, otherwise not possible to add new line
event.stopPropagation();
event.preventDefault();
}
var nextIndex = parseInt(event.target.getAttribute('tabindex')) + 1;
// Move focus to next element
// TODO: find next visible element
var nextElem = element[0].querySelector('[tabIndex="' + (nextIndex) + '"]');
if (nextElem) {
nextElem.focus();
}
}
});
formElements[i].setAttribute(procAttr, true); // Add attribute to prevent adding 2 listeners on same element
}
});
}
};
});
Event should be in HTML component (keypress) = "keyFocus($event)"
Method shoulb be like .ts file.
keyFocus(input1){
input1.srcElement.nextElementSibling.focus();
}
AngularJS already contains a light version of jQuery so you can as well use it...
http://docs.angularjs.org/api/angular.element
You could try something like this:
element.next().focus()

Truncated text with jEditable

So I have an editable line of text on my website. Whenever the text is changed and is above a certain length, I truncate the text.
Simplified jsfiddle here - http://jsfiddle.net/3kwCr/1/
On subsequent clicks on the text to edit, the truncated value with ellipsis is picked up. How do I get jEditable to pick up the actual value which is present as an attribute in the div?
data: function() { $('.editable-value').attr('value') }
will not work as I have several of these editable lines of text
I need something like
data: function() { this.attr('value') }
where this would the div object to which .editable has been applied to.
Just wrap this into jQuery object so you can use jQuery methods on it. Below is updated code. I also updated the example jsFiddle.
$('.editable').editable(function(value, settings) {
$(this).attr('value', value);
if (value.length > 10) {
return(value.slice(0,10)) + '...';
} else {
return(value);
}
}, {
data : function(value) { return($(this).attr('value')); },
type : 'text',
submit : 'OK'
});

Codemirror 3 multiplexing modes using simpleHint

So I'm trying to make an SCXML editor which is basically XML (state machine) with JavaScript blocks in it. I'm close, but I'm having trouble adding hints. It seems to boil down to I don't know the editing mode I'm in when it comes time to hint. I've looked in the CodeMirror object for clues but I'm not seeing it. I'm doing the multiplexing like so:
CodeMirror.defineMode("scxml", function (config) {
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/xml"),
{
open: "<script>", close: "</script>",
mode: CodeMirror.getMode(config, "text/javascript"),
delimStyle: "delimit"
}
);
});
editorXml = CodeMirror.fromTextArea(document.getElementById("editXmlFile"), {
lineNumbers: true,
mode: 'scxml',
indentUnit: 4,
autoCloseTags: true,
matchBrackets: true,
extraKeys: {
"'>'": function (cm) { cm.closeTag(cm, '>'); },
"'/'": function (cm) { cm.closeTag(cm, '/'); },
"' '": function (cm) { CodeMirror.xmlHint(cm, ' '); },
"'<'": function (cm) { CodeMirror.xmlHint(cm, '<'); },
"Ctrl-Space": function (cm) { CodeMirror.xmlHint(cm, ''); }
}
});
Note in the extraKeys where the XML hinting is working, how do I get the JavaScript hinting in there? From the JavaScript hinting help, it appears I'd do something along the lines of:
CodeMirror.commands.autocomplete = function(cm) {
CodeMirror.simpleHint(cm, CodeMirror.javascriptHint);
}
... extraKeys: {"Ctrl-Space": "autocomplete"} ...
But either way, I need to know the mode I'm in (XML or JavaScript) to know to use simpleHint versus xmlHint. Anyone know how this might be done?
EDIT: cm.getMode().name and cm.getOption('mode') just return scxml when I'm in either section
Thanks!
I think you should be able to dispatch on CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(POS).state).mode.name, where POS is the {line, ch} position that you're interested in. It will return a name like "xml" or "javascript", describing the inner mode at that position.

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});