How to use. selectOption() in autocomplete? - javascript

On page load I want to initialize the autocoplete with one specific option. I am using MaterializeCSS The documentation says
Select a specific autocomplete options.
Arguments
Element: Element of the autocomplete option.
instance.selectOption(el);
I tried
//autocomplete.selectOption("Radek")
//autocomplete.selectOption({"Radek"})
autocomplete.selectOption({"Radek":null})
but nothing worked. Could you suggest how to select autocomplete option programaticaly?
var elemOptions = {
data: {
"Radek Surname ": null,
"Radek": null,
"Radoslav": null
},
minLength : 2,
}
var elemAutomplete = document.getElementById('autocomplete-input1')
var autocomplete = M.Autocomplete.init(elemAutomplete, elemOptions);
//autocomplete.selectOption("Radek")
//autocomplete.selectOption({"Radek"})
autocomplete.selectOption({"Radek":null})
and working jsFiddle

Wow I just notice this question.
Let's just clear out something, basically Materialize Autocomplete is just a normal Materialize Input-Field but with an extra feature like dropdown options showing up when you click or type some text.
So, in order to do what you want, you must set the text value as exactly as the previously selected options text. This will make the label overlapping so you must add class active to the Autocomplete label (just like normally setting text value to an input field).
var elemOptions = {
data: {
"Radek Surname ": null,
"Radek": null,
"Radoslav": null
},
minLength : 2,
}
var elemAutomplete = document.getElementById('autocomplete-input1')
// getting the label element
var elemAutompleteLabel = document.getElementById('autocomplete-input1-label')
var autocomplete = M.Autocomplete.init(elemAutomplete, elemOptions);
// set the input element value
elemAutomplete.value = "Radek"
// then add class 'active' to the input label
elemAutompleteLabel.classList.add('active');
You must note that the elemAutomplete.value must be match with one of the elemOptions data.
[edited]
Only Dogfalo and God who knows what .selectOption(); did.

Related

restrict the user from typing a new name and allow only to select from existing list

I'm working on autocomplete textbox feature of angularjs. I want the user only to select name from the existing autocomplete list instead of typing a new name. Eg.,When user types 'Al' autocomplete list shows the matching list and user can select one name from the existing list instead of typing a new name.How to restrict user from submitting a new name which is not present in the existing list.
Demo : http://plnkr.co/edit/AdmtP1b6K9kQorMHmt7t?p=preview
Code Sample:
$scope.countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei"];
$scope.validateField = function(){
alert("Clicked on submit , validte field");
}
$scope.complete=function(string){
var output=[];
angular.forEach($scope.countryList,function(country){
if(country.toLowerCase().indexOf(string.toLowerCase())>=0){
output.push(country);
}
});
$scope.filterCountry=output;
}
$scope.fillTextbox=function(string){
$scope.country=string;
$scope.filterCountry=null;
}
Any inputs would be helpful.
You can disable submit button and also highlight the border of the input field red, telling user to select name from drop down list.
First you need to update your complete() function. Use an else if statement that will check if the value is from the list or not, if not then you can implement your desired logic in that else if statement.
This method is flexible and easy to customize your error generation messages. You can show and hide the div that has the error message or you can apply css style on input-field using ng-style or ng-class. Right now I'll show you how to disable or enable button. Here is the updated code snippet:
$scope.complete = function(string) {
var output = [];
angular.forEach($scope.countryList, function(country) {
if (country.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(country);
$scope.enableDisable = false;
} else if (country.toLowerCase().indexOf(string.toLowerCase()) < 0) {
$scope.enableDisable = true;
}
});
$scope.filterCountry = output;
}
And the In the html section you just need to add ng-disabled attribute and set its value.
<input type="submit" value="submit" ng-disabled="enableDisable" ng-click="validateField()">
So, you can do whatever you want in that else if statement to get the desire error message.
Take a look at this plunkr.
you can check for the validity of input using something like below and monitoring the value using ng-change
$scope.checkInput = function(){
$scope.validInput = $scope.countryList.indexOf($scope.country) > -1;
}

jQuery ui autocomplete get selected item in other function

I have a problem with jQuery autocomplete, I try to get the value of the input but I get the label but no the value.
var listeClients = [{"value":1,"label":"Orange"},{"value":2,"label":"Blue"}];
$( "#site_client_first" ).autocomplete({
source: listeClients,
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
And for get the value I use :
$("#site_client_first").val();
https://jsfiddle.net/fyz8vL3a/
How to get the value ?
Thanks by advance =)
In the select event of autocomplete, you are setting the label as value property of element #site_client_first i.e. here $("#site_client_first").val(ui.item.label). Hence when you try to set the span's innerHTML by assigning $("#site_client_first").val(), you will always get the label and not your item.value.
Try the code below. I have added an attribute 'itemValue' to $("#site_client_first"). This will hold your item's value and $("#site_client_first").val() will hold the item's label.
And when setting up the span innerhtml, you assign $("#site_client_first").attr("itemValue") which is your item's value.
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
Make change to the above line in your HTML change.
Your final html is as belows:
<input class="form-control" name="site[client]" id="site_client_first" itemValue="100" />
<button onclick="getValue()">Get</button>
<span id="svalue"></span>
Your script goes here:
$(document).ready(function() {
var listeClients = [{ "value": 1, "label": "Orange"}, {
"value": 2,
"label": "Blue"
}];
$("#site_client_first").autocomplete({
source: listeClients,
select: function(event, ui) {
$("#site_client_first").val(ui.item.label);
$("#site_client_first").attr("itemValue", ui.item.value);
return false;
}
});
})
var getValue = function() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}
function getValue() {
document.getElementById("value").innerHTML = $("#site_client_first").attr("itemValue");
}
The problem is you are trying to use an input element as a select element.
Unlike for a select, the value for an input is simply what is written in it.
The default behavior of the autocomplete plugin is to display the labels of given source as suggestions, and when you select one them it sets the corresponding value in the input. You are overriding this functionality in the code below, by setting the label as value of the input:
select: function (event, ui) {
$("#site_client_first").val(ui.item.label);
return false;
}
If you were to remove the piece of code above, you would notice that the value field will be written in the input element upon selection of an option.
Solution 1
I recommend replacing your input element with a select one. Which I think better suits your needs. If you need to search through the options you may want to use a plugin like chosen or select2.
Solution 2
If you're keen on using an input with autocomplete, set the value as an extra attribute in the select callback
select: function (event, ui) {
$("#site_client_first").val(ui.item.label); // what the user sees
$("#site_client_first").attr('data-realValue', ui.item.value); // value is hidden
return false;
}
You can retrieve the value using
$("#site_client_first").attr('data-realValue');
Demo: https://jsfiddle.net/fyz8vL3a/1/

Hiding field of custom-multi-field using javascript in listener

I have customized form of multi-field in a component having two variations.
In one variation of my component I want to hide a field (title) which is inside custom-multi-field . I am using the following JavaScript code in listener.
This code is not working. Where am I wrong?
function() {
var dialog = this.findParentByType('dialog');
var contenttype = dialog.getField("./type").getValue();
var teaserlinks = dialog.getField("./teaserlinks");
var title = dialog.getField("./teaserlinks").getField("./title");
alert(title);
if(contenttype == 'variation-1'){
teaserlinks.show();
title.hide();
}
else if(contenttype == 'variation-2'){
teaserlinks.show();
}
}
Try using the hidden property of node. Initially set the hidden property to true and in javascript file change the hidden property to false (or as per your requirement).
Few imp points first before answer:
you have to write listener in your widget file only.
below is the sample code where in I have 2 fields. 1st field is mytext field and another field is myselection. On changing the value in myselection field I am toggling visibility of my text field.
Below is snippet:
this.mytext = new CQ.form.textField({...})
this.myselection = new CQ.form.Selection({
fieldLabel:"my selection",
type:"select",
width : "325",
allowBlank:false,
defaultType:"String[]",
fieldDescription : "Select value from dropdown",
options: "/a/b/c.json",
listeners : {
selectionchanged : function(){
var mytext = this.findParentByType('mywidget').mytext;
mytext.hide();
}
}
});
I hope this will be helpful.
I have no knowledge about aem and Adobe CQ5 but I can give you some hints how to debug your script.
First of all don't use alert for debugging! (BTW what does alert(title); show?)
I would recommend to open the browser console (e.g. Press <F12> on Firefox and switch to the tab "Console").
Herein the browser displays all exceptions and error messages. Additionally you can output some text with console.log("...");` from your script.
Here is my edit of your program. Perhaps the output can help you.
function()
{
var dialog = this.findParentByType('dialog');
var contenttype = dialog.getField("./type").getValue();
var teaserlinks = dialog.getField("./teaserlinks");
var title = dialog.getField("./teaserlinks").getField("./title");
console.dir(title);
console.log(contenttype);
teaserlinks.show();
if(contenttype == 'variation-1')
{
title.hide();
}
else if(contenttype == 'variation-2')
{
title.show();
}
}
And, console.dir(<object>); shows you the object structure to one level deep.

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

filtering only previously unselected <select> options qith JQuery

Previously I asked how to do this and was directed to this:
<script>
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
</script>
(http://www.lessanvaezi.com/filter-select-list-options/)
When I use this filter on the select box it filters both the unselected AND the selected. I'd like it to ONLY filter the unselected because if a user wants to ammend the selections and filters again, the previously selected items go away - unless they meet the filter criteria.
I'm not that good at JavaScript or JQuery and can't understand how I might tell the above script to ignore options that are ":selected" but filter all else.
Here's a jfiddle if it helps: http://jsfiddle.net/UmKXy/ I'd like option one and two to remain selected and in the list when user begins to type.
Thanks for help!
The solution you had would not work with selected elements because he created an array of options at the start and then matched those options against the regex(Without regards to what is actually selected). I've used spans to hide options in the past and created an example for you to see how it works. Here is the link : http://jsfiddle.net/rD6wv/
Here is the code
$(function() {
$("#filterByText").bind('keyup',function(){
var search = $.trim($(this).val());
var regex = new RegExp(search,"gi");
$("#filez").find('option').each(function(){
if(!$(this).is(':selected')){
if($(this).val().match(regex) === null) {
$(this).wrap('<span>');
}else if($(this).parent().is('span')){
$(this).parent().replaceWith($(this));
}
}
});
});
});
You simply need to loop through all the options of the select when you type in the textbox.
You then check if it is selected, if it is you do nothing, else you check if it matches the search filter, if it does you wrap it in a span, making it invisible, else it means you need to see it, so you check if it is already wrapped in a span, and in that case you replace it with the option so you can see it again.
to selected the non selected options, use this:
$('option:not[selected]') or $('#myselect > option:not[selected]')
to remove them, use this:
$('option:not[selected]').remove();
in css, :not filters for opposite of what comes in the curved brackets.
and [] is attribute selector.
so :not[selected] means: does not have an attribute whose key is "selected"

Categories

Resources