Handle selected event in autocomplete textbox using bootstrap Typeahead? - autocomplete

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;
}
});
});

Related

ComboBox with entered text filtering - SAP UI5

I have had a select control where I could select from user names. Now I want to convert that select into combo box so I can give the user ability to enter text as well. The values populated in the combo box are in text property as {FirstName}, {LastName}. I do not want to use additional text as it shows at end of the row wih lot of space in between. My issue with Combo box is :
Values get populated but how do I filter? There is already some logic that is written on change method. I want to do custom filtering on the values. For example: If I write "P" it should show all the values that have P in the text (First name and last name). Where to write filter function? Also I found custom filtering code in demokit, I want to use it - but when I use it in inti method under delegate, I get error - this.get....setfilterfunction().. is not a function
View.xml
<ComboBox items= "{path:'items>/name'}" id="A"
selectedKey="{item>/Header/Name}" change="nameSelected">
<core:ListItem key="{order>NameID}" text="{order>LastName} ,{order>FirstName}"/>
</ComboBox>
Controller.js
_initializeData: function () {
var name = this.getView().byId("A");
name.addEventDelegate({
onAfterRendering: function() {
this.getView().byId("A").setFilterFunction(function(sTerm, oItem) {
return oItem.getText().match(new RegExp(sTerm, "i")) ||
oItem.getKey().match(new RegExp(sTerm, "i"));
});
}
},
nameSelected: function () {
......some logic processing..
}
You have to bind this in your function. I guess.
Can you access this.getView().byId("A") , when you put a break point in the onAfterRendering part ?
Try this solution: You are not working in the right scope.
_initializeData: function () {
var name = this.getView().byId("A");
name.addEventDelegate({
onAfterRendering: this.setFilter.bind(this) });
},
setFilter: function() {
this.getView().byId("A").setFilterFunction(function(sTerm, oItem) {
return oItem.getText().match(new RegExp(sTerm, "i")) ||
oItem.getKey().match(new RegExp(sTerm, "i"));
});
},

How can we validate just the mandatory fields in a form in SAP UI5?

I am trying to create a form which has some mandatory fields that requires validation on form submission.
Could anyone suggest me the best possible way to do that in SAP UI5? The mandatory fields are in greater number, thus i don't want to check all fields separately by their ID.
You can do this in two scenarios. While entering a value, or when submitting the form as in your question.
CheckRequired: function(oEvent) {
var aInputs = [this.getView().byId(oEvent.getSource().getId())];
var sError = false;
jQuery.each(aInputs, function(i, input) {
if (!input.getValue() || input.getValue().length < 1) {
input.setValueState("Error");
input.focus();
sError = true;
} else {
input.setValueState("None");
}
});
return sError;
},
This function is to be used with the onLiveChange property. It checks if the control is filled with at least one character.
If you would like to check everything when you press submit. you could use a function like this with your form:
_onSubmitCheck: function() {
var oForm = this.getView().byId("form").getContent();
var sError = false;
oForm.forEach(function(Field) {
if (typeof Field.getValue === "function") {
if (!Field.getValue() || Field.getValue().length < 1) {
Field.setValueState("Error");
sError = true;
}
else {
Field.setValueState("None");
}
}
});
return sError;
},
It will loop over your form controls to check if the getValue() method exists as part of the control. If that returns yes, it wil check if it has a value of at least 1 character.
There are kind of two ways.
add
"sap.ui5": {
...
"handleValidation": true,
to your manifest.json and type & constraints to your inputs
<Input type="Text" value="{path: 'NoFioriValidationsInDefault', type: 'sap.ui.model.type.String', constraints: { minLength:2 }}" valueLiveUpdate="true" enabled="{= ${editView>/nfvid/enabled} && ${editView>/creating}}" visible="true" width="auto" valueHelpOnly="false" maxLength="0" id="inp_cond_nfvid" required="{editView>/nfvid/required}"/>
This gives just visual feedback to the user, if you need the status in your controller you can either iterate over all the inputs and check them by hand, or use https://github.com/qualiture/ui5-validator
Just by calling
var validator = new Validator();
validator.validate(this.byId("form1"));
if (!validator.isValid()){
//do something additional to drawing red borders? message box?
return;
}
in your controller, the view will mark missing required inputs with the ValueState.ERROR (red borders) and tell you if all inputs inside the supplied control are valid.
I am doing it the old-school way. The input fields do get the required=true property and then I loop over all controls found with this property:
// store view ID to compare with control IDs later
var viewId = this.getView().getId();
jQuery('input[required=required]').each(function () {
// control has wrapper with no id, therefore we need to remove the "-inner" end
var oControl = sap.ui.getCore().byId(this.id.replace(/-inner/g,''));
// CAUTION: as OpenUI5 keeps all loaded views in DOM, ensure that the controls found belong to the current view
if (oControl.getId().startsWith(viewId) && (oControl instanceof sap.m.Input || oControl instanceof sap.m.DatePicker)) {
var val = oControl.getValue();
if (!val) {
oControl.setValueState(sap.ui.core.ValueState.Error);
oControl.openValueStateMessage();
bError = true;
return false;
} else {
oControl.setValueState(sap.ui.core.ValueState.None);
oControl.closeValueStateMessage();
}
}
});
HTH,
Anton

Ajax AutoComplete for jQuery "onEmpty"-type of event

I'm using Ajax Autocomplete for Jquery (https://www.devbridge.com/sourcery/components/jquery-autocomplete/) with DataTables to search on a specific column.
Using onSearchComplete and onSelect from Autocomplete I can filter both the input and the table together as the user is typing (onSearchComplete) and when they select an entry (onSelect):
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSearchComplete: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion);
},
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion);
}
});
function update_scoreboard_by_site_name_filter(suggestion) {
var colname = "site_name:name";
if (scoreboard.column(colname).search() !== suggestion) {
scoreboard.column(colname).search(suggestion).draw();
}
};
However, when the input is deleted, then the DataTable is left filtered on the last input because neither event is fired in that case.
I've tried the keyup and change events on the input itself to pass an empty string to the DataTable search:
$("#scoreboard_site_name_filter").on("keyup change", function() {
var suggestion = "";
update_scoreboard_by_site_name_filter(suggestion);
});
If I place it before the autocomplete then it has no affect and if I place it after then of course I lose the ability to filter the table as I type because it fires after the autocomplete.
How can I detect when the input has been deleted and then re-filter the table on an empty string (i.e., clear that filter)?
OK, I was overthinking it . . .
I removed the onSearchComplete event and just went with the input event on the input itself and everything is working great.
I left the onSelect for the Autocomplete and am now properly passing suggestion.value instead of suggestion.
Here's the proper code for anyone interested:
$("#scoreboard_site_name_filter").on("keyup change", function() {
update_scoreboard_by_site_name_filter(this.value);
});
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion.value);
}
});
function update_scoreboard_by_site_name_filter(suggestion) {
var colname = "site_name:name";
if (scoreboard.column(colname).search() !== suggestion) {
scoreboard.column(colname).search(suggestion).draw();
}
};
Additionally I updated the code to make the search regex if the suggestion is actually selected (clicked on or entered on) and to add a class to the input as an indicator that the table is now filtered on that exact search term:
$("#scoreboard_site_name_filter").on("input", function() {
update_scoreboard_by_site_name_filter(this.value, false);
});
$("#scoreboard_site_name_filter").autocomplete({
serviceUrl: "/wiki/extensions/CFBHA/models/_mSiteNames.php",
onSelect: function(suggestion) {
update_scoreboard_by_site_name_filter(suggestion.value, true);
}
});
function update_scoreboard_by_site_name_filter(suggestion, selected) {
var colname = "site_name:name";
if (!selected) {
scoreboard.column(colname).search(suggestion).draw();
$("#scoreboard_site_name_filter").removeClass("autocomplete-input-selected");
} else {
scoreboard.column(colname).search("^" + suggestion + "$", true, false).draw();
$("#scoreboard_site_name_filter").addClass("autocomplete-input-selected");
};
};

jQuery Autocomplete id and item

I have a working query autocomplete code that completes the full_name when letters are typing. What I am trying to figure out is how to get the user_id for that goes with the full_name. I have JSON that comes back like so:
[{"full_name":"Matt","user_id":"2"},{"full_name":"Jack","user_id":"9"},{"full_name":"Ace","user_id":"10"},{"full_name":"tempaccount","user_id":"11"},{"full_name":"Garrett","user_id":"26"},{"full_name":"Joe","user_id":"29"},{"full_name":"Raptors","user_id":"32"}]
Below is my jQuery code. I am using PHPfox framework.
$(function(){
//attach autocomplete
$("#to").autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
//$.getJSON("friends.php?callback=?", req, function(data) {
$.ajaxCall('phpfoxsamplee.auto', 'startsWith='+req.term)
.done(function( data ) {
//create array for response objects
var suggestions = [];
var data = $.parseJSON(data);
//process response
$.each(data, function(i, val){
//suggestions.push(val.full_name,val.user_id); (This works and shows both the full name and id in the dropdown. I want the name to be visible and the ID to goto a hidden input field)
suggestions.push({
id: val.user_id,
name: val.full_name
});
});
//pass array to callback
add(suggestions);
});
},
//define select handler
select: function(e, ui) {
//create formatted friend
alert(ui.item.full_name); //Trying to view the full_name (doesn't work)
alert(ui.item.id); // trying to view the id (doesn't work)
var friend = ui.item.full_name, (doesn't work)
//var friend = ui.item.value, (This works if I do not try to push labels with values)
span = $("<span>").text(friend),
a = $("<a>").addClass("remove").attr({
href: "javascript:",
title: "Remove " + friend
}).text("x").appendTo(span);
//add friend to friend div
span.insertBefore("#to");
$("#to").attr("disabled",true);
$("#to").attr('name','test').attr('value', 'yes');
$("#to").hide();
},
//define select handler
change: function() {
//prevent 'to' field being updated and correct position
$("#to").val("").css("top", 2);
}
});
//add click handler to friends div
$("#friends").click(function(){
//focus 'to' field
$("#to").focus();
});
//add live handler for clicks on remove links
$(".remove", document.getElementById("friends")).live("click", function(){
//remove current friend
$(this).parent().remove();
$("#to").removeAttr("disabled");
$("#to").show();
//correct 'to' field position
if($("#friends span").length === 0) {
$("#to").css("top", 0);
}
});
});
HTML
<div id=friends class=ui-help-clearfix>
<input id='to' type=text name='player[" . $num . "][name]'></input>
</div>
Consider the JQuery Autocomplete Combobox. It is not a standard widget, but you can pretty much paste their source. And it will enable you to capture values corresponding to text selections.

Mootools stop form submit method

I don't want to use an <input type=submit /> button to submit a form and I am instead using an <a> element. This is due to styling requirements. So I have this code:
myButton.addEvent('click', function() {
document.id('myForm').submit();
});
However, I have also written a class that improves and implements the placeholder attribute on inputs and textareas:
var FDPlaceholderText = new Class({
Implements: Events,
initialize: function() {
var _self = this;
var forms = document.getElements('form');
forms.each(function(form) { // All forms
var performInit = false;
var i = 0;
var ph = [];
form.getElements('input, textarea').each(function(el) { // Get form inputs and textareas
if (el.getProperty('placeholder') != null) { // Check for placeholder attribute
performInit = true;
ph[i] = _self.initPlaceholder(el); // Assign the placeholder replacement to the elements
}
i ++;
});
if (performInit) {
_self.clearOnSubmit(form, ph);
}
});
},
clearOnSubmit: function(form, ph) {
form.addEvent('submit', function(e) {
ph.each(function(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
});
});
},
initPlaceholder: function(el) {
el.defaultValue = el.getProperty('placeholder');
el.value = el.getProperty('placeholder');
el.addEvents({
'focus': function() {
if (el.value == el.defaultValue) el.value = '';
},
'blur': function() {
if(el.value.clean() == ''){
el.value = el.defaultValue;
}
}
});
return el;
}
});
window.addEvent('domready', function() {
new FDPlaceholderText();
});
The above class works great if a form is submitted using an actual <input type=submit /> button: it listens for a submit and clears the inputs values if they are still the default ones therefore validating that they are essentially empty.
However, it seems that because I am submitting one of my forms by listening to a click event on an <a> tag the form.addEvent('submit', function(e) { isn't getting fired.
Any help is appreciated.
well you can change the click handler to fireEvent() instead of call the .submit() directly:
myButton.addEvent('click', function() {
document.id('myForm').fireEvent('submit');
});
keep in mind a couple of things (or more).
placeholder values to elements that lack placeholder= attribute is pointless
if you detect placeholder support, do so once and not on every element, it won't change suddenly midway through the loop. you can go something like var supportsPlaceholder = !!('placeholder' in document.createElement('input')); - remember, there is no need to do anything if the browser supports it and currently, near enough 60% do.
you can otherwise do !supportsPlaceholder && el.get('placeholder') && self.initPlaceholder(el); - which avoids checking attributes when no need
when the form is being submitted you really need to clear placeholder= values in older browser or validation for 'required' etc will fail. if validation still fails, you have to reinstate the placeholder, so you need a more flexible event pattern
avoid using direct references to object properties like el.value - use the accessors like el.get('value') instead (for 1.12 it's getProperty)
for more complex examples of how to deal with this in mootools, see my repo here: https://github.com/DimitarChristoff/mooPlaceholder
This is because the submit() method is not from MooTools but a native one.
Maybe you can use a <button type="submit"> for your styling requirements instead.