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
Related
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 ''
}
I have a blade template with a search bar, which has no submit button and is used for filtering. However, I can't seem to get it to filter appropriately, as the page was originally using angular (which has been removed completely).
My page displays all of my products using foreach loops and displays the info from variables in my page controller (pulling everything from the database and storing as variables). Anyway, everything displays fine but I need help getting this to filter properly.
Basically, if a term entered in the search bar is anywhere in the JSON object gathered by the controller, then I want it to only display those objects. I may even need another foreach loop.
Here's the html/blade code:
<!--Search bar div-->
<div class="uk-width-5-10">
<div class="md-input-wrapper search-form">
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
</div>
<!--foreach loops around the wrapper that shows products, for reference-->
#foreach ($orderFormData->pgroups as $pgroup)
#foreach ($pgroup->image_names as $image_name)
#foreach ($pgroup->pskus as $psku)
Javascript for the search (see the variable for the JSON object, that's what I need to search within)
<script>
var orderFormData = <?php echo json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
Is there a better way I should be doing this? I may even need to do a foreach loop around the search bar
It kind of sounds like you're looking for an auto complete. Have you looked at the jquery-ui-autocomplete library? It's pretty easy to implement, and might add more functionality more easily than writing loops yourself.
https://jqueryui.com/autocomplete/
I'll get into why I named the function below, but here's my implementation:
monkeyPatchAutocomplete();
$("#your_searchbox_selector").autocomplete({
source: // http://Your_Search_URL_endpoint_here,
delay: 500, // prevents search from running on *every* keystroke
minLength: 1, // default is 2, change or remove as you like
// open page after selecting (with enter key).
select: function( event, ui )
{
var qval = ui.item.id // this pulls whatever field you're looking for in your JSON that you want to use to direct your user to the new page, in my case "id";
var url = 'http://whereever_you_want_your_user_to_go?';
window.location = url + qval;
}
});
For my implementation, I wanted to color code the results in my autocomplete list with active and inactive entries, so my search controller JSON result includes 3 fields:
'value' => $searchable_values, 'id' => $id_mapping_of_whatever, 'class' => $css_classes_to_use
My search controller plugs in emails, names, and phone numbers to the value field, which is searchable, then maps an id, and plugs in css classes that I use to change the text color of the results through a monkeypatch on jQuery's autocomplete:
function monkeyPatchAutocomplete()
{
$.ui.autocomplete.prototype._renderItem = function( ul, item)
{
var re = new RegExp(this.term, 'i');
var t = item.label.replace(re,"<span class='autocomplete-span'>" + this.term + "</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a class='text-" + item.class + "'>" + t + "</a>" )
.appendTo( ul )
};
};
If you're interested in formatting your results, check out dev.e.loper's answer to: How can I custom-format the Autocomplete plug-in results?.
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>
I have found the #Olegs answer for FORM based select2 integration to jQgid, but I need help to get it to work in inline mode,, this jsfiddle is my attempt to get my problem online somehow I'm new with fiddle so please be patient :)
http://jsfiddle.net/mkdizajn/Qaa7L/58/
function(){ ... } // empty fn, take a look on jsfiddle
On this fiddle I can't make it to work to simulate the issue I have in my local network but the problem with this select2 component is that when I update some record(via local or ajax), the grid does not pick up my change and it sends null for values where select2 fields are!
I'm sorry that I can't make jsfiddle to work like on my PC :(
Thanks for any help you can think off that may be the issue here..
P.S. one veeeery strange thing is that when I console.log( select2-fields ), before, and after the value is picked up correctly but I suspect that the grid loose that value somewhere in between .. and send null values to server..
I'm posting this in a good will that I think will help anyone if come to close incounter with similar problem like me..
I'll try to bullet this problem out step by step..
first, on my server side I generate one html tag somewhere near grid table that holds info what columns, fields are lookup type.. like this:
<div id="hold_lookup_<?=$unique_id?>" style="display: none"><?php echo $lokki; ?></div>
that gives me output like this:
<div id="hold_lookup_table1" style="display: none">col1+++col2+++col3</div>
define onselectrow event somewhere
$onSelectRow = "function(){
f = $(this).attr('id'); // grid name
try{
n = $('#hold_lookup_' + f).text().split('+++');
}catch(e){
console.log(e)
}
rez = ''; // results
temp = 'textarea[name='; // template
$.each(n, function(index, item){
rez += temp + item + '],'
});
rez = rez.slice(0,-1); // rezemo zadnji zarez
$( rez ).select2({ .. define my ajax, my init etc.. });
}";
$dg->add_event("jqGridInlineEditRow", $onSelectRow);
last but very tricky part is here.. I destroy select2 columns before sending to database in jqgrid.src file where function for SAVE inline method is.. like this
if (o.save) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.savetext || '',
title: o.savetitle || 'Save row',
buttonicon: o.saveicon,
position: "first",
id: $t.p.id + "_ilsave",
onClickButton: function() {
var sr = $t.p.savedRow[0].id;
rez = rez.split(',');
rez1 = '';
$.each(rez, function(index, item) {
rez1 += item + ','
})
rez1 = rez1.slice(0, -1);
rez1 = rez1.split(',');
$.each(rez1, function(index, item) {
$(item).select2('destroy');
});
you can see that I inserted the code onclickbutton event via same 'rez' variable that was defined in my php file where I created grid..
That's it, I hope that helped someone, event if not in this particular problem, but with methods that was used here :)
cheers, kreso
Using Kendo UI and a Row Template, I have a grid started like the following:
http://jsfiddle.net/xF4CK/
I'm wanting to alter the Actions column to contain a drop down list populated by the actions object. The actions object contains display text and a relative url path like the following example:
var actions = [
{ name: "edit", url: "reports/report/1" },
{ name: "delete", url: "reports/delete/1" }
];
This actions object is on each row of the grid and may vary per row/user/etc. The intended usage would be a user selects the drop down list and then chooses one of the options. On choosing the option the url value is posted.
I'm not sure where to begin, or if it is possible in the Row Template. Any help is greatly appreciated.
I was able to get it figured out. In the row template I am calling a js function and returning html markup for the list. Then setting the .kendoDropDownList on all items based on a class attribute. I have updated the jsfiddle here but it doesn't seem to work in jsfiddle. It is working when I test in IE10 and Chrome on my dev machine.
Here's the relevant code changes:
In the rowTemplate, changed
#: actions #
to
#= renderDropDown(actions) #
This "=" displays the literal text which renders the html as html whereas the ":" encodes the html.
The renderDropDown function:
function renderDropDown(actions) {
var dropDownList = "<select class=\"insight-dropdown\">";
dropDownList = dropDownList + "<option value=\"default\" disable=\"disabled\">...</option>";
for (var i = 0; i < actions.length; i++) {
dropDownList = dropDownList + "<option value=\"" + actions[i].url + "\">" + actions[i].name + "</option>";
}
dropDownList = dropDownList + "</select>";
return dropDownList;
}
To the dataBound event of the grid, I added this function to turn the html into a drop down list:
// Set the drop down lists
$(".insight-dropdown").kendoDropDownList({
select: onDDLSelect
});
To handle the selection of an action:
function onDDLSelect(e) {
var dataItem = this.dataItem(e.item.index());
alert(dataItem.value);
}