Select2 ignore certain input? - javascript

So I'm using the Select2 JQuery based replacement for select boxes.
I've set it up (with help from an example I found) for remote data searching via ajax which works great. I've got a minimum input value of 3 so the user has to enter at least 3 characters before the search starts (otherwise "A" would return 90% of the searchable values).
Unfortunately a large portion of my searchable values also start with "The". So if a user types "The", 50% of the results get returned, populating a huge dropdown with basically unfiltered results ... not ideal!
Is there any way to get Select2 to ignore certain set phrases, ie typing "The" shouldn't count towards the minimum 3 character count!
$('#searchInput').select2({
minimumInputLength: 3,
placeholder: 'Please search here ...',
ajax: {
url: "/api/v1/institutes",
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
query: term
};
},
results: function(data, page ) {
return { results: data }
}
},
formatResult: function(institute) {
return "<div class='select2-user-result'>" + institute.name + "</div>";
},
formatSelection: function(institute) {
return institute.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"term":elementText});
}
});

You can check Select2 docs - search, where you can customize to match your pattern.

I faced the same problem. I solved the problem by using "data-minimum-input-length" attribute in html code.
<select id="mySelect" data-minimum-input-length="3"></select>

Related

how to Disable / Enable button in datatable

I want to check the Article's Status, if true the Edit button will be disabled else the user can click and switch to the Edit page. How to use it?
return ' Edit ';
}}
],
order: [1, 'asc']
});
The column render function you are using:
render: function (data) { ... }
is capable of accessing all the data in the current row. Its full signature is:
render: function ( data, type, row, meta ) { ... }
So, you can use the row parameter to access other columns in that row, such as row.status:
{
data: 'id',
className: "center",
title: 'Actions',
render: function (data, type, row, meta) {
if (row.status === true) {
return ' Edit ';
} else {
return '<a href="Student/EditArticle/' + data + '" class="btn btn-success mr-1" disabled> Edit </a>';
}
}
}
You can see further details and examples here.
It is worth looking at why the type parameter is provided and how it is used. It basically helps you to provide multiple versions of a value - one value for the table display (the HTML link); a different value for sorting; another value for filtering, and so on.
So, for example, for your clickable link, you may prefer the sort and filter values to be simply the data value (without any of the extraneous HTML).
But this is completely optional - you don't have to use it. See orthogonal data for more info.
Update:
I forgot that a hyperlink cannot be disabled in the same way as a button (so you cannot use "disabled"). Instead, you can look at these approaches, or do what TimRoberts suggested in your question's comments. Having said that, the render function with the row parameter should be what you need.
else {
return 'Edit'; // or, alternatively: return ''
}

Display two different values in autocomplete

I'm trying to set an autocomplete that would display 2 values in the dropdown list. Precisely, i have a users database with names and ID, and i want search an user by typing his name, and then have the choice between all users that have this name.
Example : i have two users called Jack, with ID 1 and 2
I want to be able to select which Jack i want by seing the IDs in the dropdown list
Here's my actual code :
HTML
<div class="col-sm-3 col-md-3">
<form>
Nom: <input type="text" id="ag_nom_pub" value="Oih"> <!-- this is the field used for the autocomplete -->
</form>
</div>`
JS :
$('#ag_nom_pub').autocomplete({
// This shows the min length of charcters that must be typed before the autocomplete looks for a match.
minLength: 3,source: function (request, response) {
response($.map(ag_pandaone_webservice('ag_publicitaire_get_list',$('#ag_nom_pub').val(), function (value, key) {
return {
label: value.NOMPUBLICITAIRE,
value: value.ENTITYID
}
})));
},
focus: function(event, ui) {
$('#ag_nom_pub').val(ui.item.NOMPUBLICITAIRE);
return false;
},
// Once a value in the drop down list is selected, do the following:
select: function(event, ui) {
// place the person.given_name value into the textfield called 'select_origin'...
$('#ag_nom_pub').val(ui.item.NOMPUBLICITAIRE);
// and place the person.id into the hidden textfield called 'link_origin_id'.
$('#idPub').val(ui.item.ENTITYID);
return false;
}
});
The NOMPUBLICITAIRE and ENTITYID are the name of the variables from the users database i want to display in my list.
The $.map(ag_pandaone_webservice('ag_publicitaire_get_list',$('#ag_nom_pub').val()
return an array of object which contains the ID and the name of the user
The actual code i have was taken from here
At the moment i'm getting this error when i type 3 letters in my input field :
I've been looking on the internet for this error but i don't really understand what causes it and i don't know what can i do to fix it.
If anyone could help me in any way i'd be grateful :)
Don't hesitate to tell me if you need more information from my code or attempts to fix the damn thing !
Thanks in advance and have a great day !
Try to override the _renderItem function of autocomplete like this :
For jQuery UI before 1.10 :
$('#ag_nom_pub').autocomplete({
// Your options goes there
}).data("autocomplete")._renderItem = function (ul, item) {
// Here you are returning the element wich will be rendered
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.ENTITYID + " - " + item.NOMPUBLICITAIRE + "</a>")
.appendTo(ul);
};
jsfiddle for versions before 1.10
For jQuery UI after 1.10:
$('#ag_nom_pub').autocomplete({
// Your options goes there
}).data("ui-autocomplete")._renderItem = function (ul, item) {
// Here you are returning the element wich will be rendered
return $("<li></li>")
.data("ui-autocomplete-item", item)
.append("<a>" + item.ENTITYID + " - " + item.NOMPUBLICITAIRE + "</a>")
.appendTo(ul);
};
jsfiddle for versions after 1.10
Before jquery UI 1.10, the data tag was autocomplete and since 1.10 it is ui-autocomplete. The same applies for item.autocomplete wich becomes ui-autocomplete-item
Bonus link: jQuery UI 1.10 Upgrade Guide about autocomplete

Selecting an autocomplete list does not save the word fully when using ajax to save

I built an autocomplete list of cities using a mysql query. Typing in the input field correctly initiates the search and builds the selectable city list. The problem is that the city name in full does not get saved, only the characters typed when using .on('change'... I tried other mouse events such as mouseover, mousemove, mouseout, mouseenter, mouseleave - and they require the user to first select the item from the list, move out, then swipe the cursor over the input a second time to actually trigger the save of the selected city name. The html looks like:
<input type="text" onmouseover="this.focus();" class="saveCity" name="pob_city" member_id="<?php echo $member_id; ?>" value="<?php echo $pob_city; ?>" placeholder="City" id="pob_city" />
<script language="javascript" type="text/javascript"> $("#pob_city").coolautosuggest({ url:"tools/autosuggest/query_cities.php?chars=" }); </script>
The saveCityCountry javascript:
$(document).on('mouseout','.saveCity',function()
{
var DATA=$(this).val();
var n =remove_whitespaces(DATA);
var MEMBER_ID=$(this).attr('member_id');
$("#Results").html( "" );
if(n !=''){
var dataString = 'pob_city='+ n +'&member_id='+MEMBER_ID;
$.ajax({
type: "POST",
url: "saveData.php",
data: dataString,
cache: false,
success: function(html)
{
$("#Results").html( html );
}
});
}
})
You can see a demo at: http://dottedi.us/misc/ajaxsave/
The other thing that is slightly bothersome is that with ordinary input fields such as first or last name, the on change event only triggers when you click somewhere else on the page, thus the placebo "Save" button.
Update: I cleaned up the code in my example splitting off City from Country and updated the post to reference saveCity. This will not affect the result, just a bit easier to follow.
Inside the http://dottedi.us/misc/ajaxsave/tools/autosuggest/js/ folder are two javascript files that might be relevant, jquery.coolautosuggest.js and jquery.coolfieldset.js. On line 46 of jquery.coolautosuggest.js I see success:function(data){. You want me to place "source: data, autoFocus: true, delay: 0, minLength: 0, select: response, response: response" somewhere in here? Please make it clear where and with the right syntax, semicolin, etc.
In the codeblock you added, I assume that I change the HTML adding the ,response and the function response just gets placed somewhere within my saveData.js. Once this is right, do I go back to change as opposed to mouseout or mouseover?
include response function in your autocomplete call, where you can assign the selected value to hidden field, This will allow you to retain full text.
I assume you are getting array of cities, store each city in an array in a key called "city" and return it.
Define one hidden field say "selected_city".
Inside your coolautosuggest success function place this code
source: data,
autoFocus: true,
delay: 0,
minLength: 0,
select: response,
response: response
$("#pob_city").coolautosuggest({ url:"tools/autosuggest/query_cities.php?chars=" },response);
function response(){
if (typeof ui.content != "undefined" && ui.content.length === 1) {
city= ui.content[0].city;
}
else if (typeof ui.item != "undefined" && ui.item.label.length > 0) {
city= ui.item.label;
}
if (label.length > 0 || index.length > 0) {
$("#selected_city").val(city);
// this value you can use to display
}
}
before doing this please change the below function on jquery.coolautosuggest.js at line 120
if(me.submitOnSelect==true){ $("form").has(me.textField).submit();
}
to
if(me.submitOnSelect==true){
$("#pob_city").val($(this).find(".suggestion_title").text()); $("form").has(me.textField).submit();
}

Select2 AJAX selected value is not appearing int he box

Select2 - Version 4.0.0-beta.3
I am working to upgrade my Select2 from 3 to 4.0. I am having issue processing the ajax request with Select2.
I have following field.
HTML
<input action="load_users" id="id_pic_credits" name="pic_credits" type="hidden">
JS
$(document).ready(function () {
$("*[action='load_users']").select2({
allowClear: true,
width: '100%',
multiple: false,
minimumInputLength: 1,
"ajax": {
"url": _url,
delay: 250,
dataType: "json",
data: function (search, page) {
return search
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data.items
};
},
cache: true
}
});
});
HTML Result
Server Response
List of dicts.
[{'id':1, 'text':'Ray of Peace'},{'id':2, 'text':'Ray of Peace2'}]
HTML Result
Problem
When i click on any of the records; I can not see if the value is actually is getting select.
When the drop down closes; i do not see the selected value.
The value of the field is changed in the HTML though; but I can not see the result.
It is my understanding that you are no longer supposed to use a hidden input element to back your Select2 control. Instead, you should always use a <select> element.
Change your html to:
<select action="load_users" id="id_pic_credits" name="pic_credits"></select>
See the "No more hidden input tags" section on the Select2 4.0 Announcement page.
jsfiddle

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

Categories

Resources