I've read almost every article i could find on how to accomplish this, but i'm still failing miserably. mostly because i'm an amateur at jQuery/Javascript.
I have a website that contains one input element. I've managed to get jQuery Autocomplete working nicely on this. The problem is that when i dynamically add additional elements using the .append method, these new elements do not work with autocomplete.
See jsfiddle: http://jsfiddle.net/aktive/r08m8vvy/
see jsfiddle for full code sample
Thankyou in advance for your help!! :)
-Dean
You must bind autocomplete after adding new elements
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
});
See example: http://jsfiddle.net/r08m8vvy/4/
I actually found that a more reliable way was to bind using 'on' with the 'focus' action to init the auto complete based on the field class and destory it on exit. This way it cleans up the garbage and only inits it once you need to.
I was using it with cloning rows though and even doing deep cloning, which would clone the plus and minus buttons for the rows, it wasn't cloning the autocomplete.
var auto_opts = {...opts...}
$('body').on('focus', '.search_field', function(){
$(this).autocomplete(auto_opts).on('blur', function(){$(this).autocomplete('destroy')});
});
It also means that you aren't forced into using the last row because it works on the field as you focus on it
See http://jsfiddle.net/r08m8vvy/2/
Give the new input an ID and call autocomplete on it. The initial autocompate call you make won't include the dynamically added inputs.
$(wrapper).append('<div><input id="' + x + '" type="text" name="mytext"/>Remove</div>'); //add input box
$( "input[id="+ x +"]" ).autocomplete({
source: availableAttributes
});
I Updated the fiddle http://jsfiddle.net/r08m8vvy/5/
You have to bind the autocomplete for new element
$(wrapper).append($('<div><input type="text" name="mytext[]"/>Remove</div>').find(":text").autocomplete({
source: availableAttributes
}));
Here is the simpler way to use autocomplete for dynamically created input fields.
$('body').on('focus', '.dynamic-input-class', function (e) {
$(this).autocomplete({
minLength: 2,
delay: 500,
source: function (request, response) {
$.ajax( {
url: "server side path that returns json data",
data: { searchText: request.term},
type: "POST",
dataType: "json",
success: function( data ) {
$("#data-success").html(data.returnedData); //returnedData is json data return from server side response
}
});
}
});
});
<script>
$(document).ready(function() {
var nhlTeams = ['Atlanta', 'Boston', 'Buffalo', 'Calgary', 'Carolina', 'Chicago', 'Colorado', 'Columbus', 'Dallas', 'Detroit', 'Edmonton', 'Florida', 'Los Angeles', 'Minnesota', 'Montreal', 'Nashville', ];
var nbaTeams = ['New Jersey', 'New Rork', 'New York', 'Ottawa', 'Philadelphia', 'Phoenix', 'Pittsburgh', 'Saint Louis', 'San Jose', 'Tampa Bay', 'Toronto Maple', 'Vancouver', 'Washington'];
var nhl = $.map(nhlTeams, function (team) { return { value: team, data: { category: 'Section A' }}; });
var nba = $.map(nbaTeams, function (team) { return { value: team, data: { category: 'Section B' } }; });
var teams = nhl.concat(nba);
// Initialize autocomplete with local lookup:
$('body').on('focus', '.db_items', function(){
$(this).autocomplete({
lookup: teams,
minChars: 1,
onSelect: function (suggestion) {
$('#selection').html('You selected: ' + suggestion.value);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
groupBy: 'category'
});
});
});
</script>
Related
I have new problem with my Select2 option. I can't clear my select box.
As in JSFiddle I do 'select' for my data. The problem lies in the fact that I can not remove the last element, or clear the whole field in my web portal, but in JSFiddle everything looks ok. My portal gives me error "Type Error: a is null" and I don't know why. Here is my code:
$.getJSON(url, function (data){
$("#mySelect").select2({
data:data,
placeholder: "Select options",
templateSelection: function(val) {
return val.text;
}
});
});
And my select:
<select id="mySelect"></select>
The problem disappears when I use other solution but then I can not invoke the relevant data for 'templateSelection'. In this solution I create options for my select, and simple use select2 but as You can see for the field 'data.version' I have the answer "undefined"
Code:
var data=[
{id:1, text: "sample_1", version: "1"},
{id:2, text: "sample_2", version: "2"}];
$.each(data, function(i,x){
$('#mySelect').append($('<option>', {
value: x.id,
text: x.text
}));
});
$("#mySelect").select2({
templateResult: function(data) {
return data.text + ' ' + data.version;
}
});
JSFIDDLE
Any sugestion why this solution work in jsfiddle, but not in my portal?
var data=[{id:1, text: "sample_1", version: "1"},{id:2, text: "sample_2", version: "2"}]
$.each(data, function(i,x){
$('#mySelect').append($('<option>', {
value: x.id,
text: x.text+" "+x.version,
}));
});
$("#mySelect").select2({
templateResult: function(data) {
return data.text;
}
});
when $ function is used to create element it can only accept html attributes of that element
I'm trying to generate dynamic form and show it when someone hit reply in comment section.
So,
First generating a form like below using Jquery.
script(type='text/javascript').
$(document).ready(function() {
var cVariable = !{JSON.stringify(data1)};
var userEmail = !{JSON.stringify(data.userEmail1)};
var serviceID = !{JSON.stringify(data._id)};
if(cVariable == 1){
var $myform = $('<form/>', {
action: '/services/shoutOutReplyAdd',
method: 'post',
name: 'reply-form'
});
$myform.append($("<input/>", {
type: 'text',
name: 'reply',
id: 'formAddReply',
placeholder: 'reply'
}));
$myform.append($("<input/>", {
type: 'hidden',
id: 'userEmail1',
name: 'userEmail1',
value: userEmail
}));
$myform.append($("<input/>", {
type: 'hidden',
id: 'serviceID',
name: 'serviceID',
value: serviceID
}));
$myform.append($("<input/>", {
type: 'submit',
id: 'btn',
value: 'Post reply'
}));
$("#reply-comment-form").append($myform);
}
});
$(function(){
$('.reply-comment').on('click', function(e){
e.preventDefault();
$(this).next('#reply-comment-form').show();
});
});
Second step is to specify HTML/Jade for the main body. I'm getting message values from the server and want to display a reply form when user clicks a reply text. Loop is executed three times.
each i in data.reply
p #{i.msg}
a(id='' class = 'reply-comment' href='') Reply
#reply-comment-form
hr
br
Also node that, in CSS, I have setup like below
#reply-comment-form{ display:none; }
I also have the JQ function that when clicking the anchor element text, it shows the form. Here is the code for it.
$(function(){
$('.reply-comment').on('click', function(e){
e.preventDefault();
$(this).next('#reply-comment-form').show();
});
});
When, I check the generated HTML, I only see form is assigned only for first instance of the "reply-comment-form" div element.
There are three comments in the DB, so I should see three instances of the form. However, I'm only seeing one instance.
Just another piece of information, code to generate a form and code to click the anchor element are both inside a common script(type='text/javascript'). block.
Any help will be appreciated.
Thanks
creating the form inside the click function did the trick.
$('.reply-comment').on('click', function(e){
var $myform = $('<form/>', {
action: '/services/shoutOutReplyAdd',
method: 'POST',
name: 'reply-form'
});
$myform.append($("<input/>", {
type: 'text',
name: 'reply',
id: 'formAddReply',
placeholder: 'reply'
}));
$myform.append($("<input/>", {
type: 'hidden',
id: 'userEmail1',
name: 'userEmail1',
value: userEmail
}));
$myform.append($("<input/>", {
type: 'hidden',
id: 'serviceID',
name: 'serviceID',
value: serviceID
}));
$myform.append($("<input/>", {
type: 'submit',
id: 'btn',
value: 'Post reply'
}));
$(this).append($myform);
e.preventDefault();
$(this).next('#reply-comment-form').show();
});
I have written a custom jquery autocomplete function to display certain values and textfields to update on selecting the value as per the code below:
<input type="text" name="promoitem" id="promoitem">
$('#promoitem').autocomplete({
source: "BckProcesses/GetPromoItems.asp",
create: function() {
$(this).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.append('<a>' + item.promodesc + '</a>')
.appendTo(ul);
}
},
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
}
});
This is what is return by the source file (GetPromoItems.asp)
[{"id": "1", "promodesc": "Ipad 4 ", "promocost": "200", "qty": "1"},{"id": "2", "promodesc": "Village Tickets", "promocost": "20", "qty": "2"}]
However, when I select the value from the ul, everything gets populated except the promoitem textfield. That fields goes to being blank.
Can anyone please let me know what could be causing this?
Thanks
Sam
Since you're providing your own logic in the select handler, you need to prevent the default action, which is to place ui.item.value in the input.
Right now, your code is running, and then jQueryUI is immediately trying to place ui.item.value in the input, which explains the empty value.
So really all you need to do is call event.preventDefault(); or return false; from the select handler:
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
event.preventDefault(); // <---
}
After spending an hour, finally got to an point that Jquery UI autocomplete sets the value to default.
Only one line needs to put and prevent Jquery default function to get the wok done.
// pincode list autocomplete
$('input[name=\'pincode\']').autocomplete({
'source': function (request, response) {
$.ajax({
url: 'index.php?route=seller/pincode/pincodeAutocomplete&filter_name=' + encodeURIComponent($('input[name=\'pincode\']').val()),
dataType: 'json',
success: function (json) {
json.unshift({
pincode_id: '',
pincode: '-- None --'
});
response($.map(json, function (item) {
return {
label: item['pincode'],
value: item['pincode_id']
}
}));
}
});
},
'select': function (event, ui) {
event.preventDefault();
$('input[name=\'pincode\']').val(ui.item.label);
$('input[name=\'pincode_id\']').val(ui.item.value);
}
});
what i am trying to do is dynamically generate WordPress tinymcs listbox values. but it seems my getValue function is not working well or its not possible to add getvalue() function to value parameter. this code is not working. please tell me how to do this. i need this for my new plugin development. sorry for bad english :(
here i have posted the code bellow
(function() {
tinymce.PluginManager.add('AP_tc_button', function( editor, url ) {
editor.addButton( 'AP_tc_button', {
text: 'My test button',
icon: 'wp_code',
onclick: function() {
editor.windowManager.open( {
title: 'Select Your AD',
body: [
{
type: 'listbox',
name: 'level',
label: 'Header level',
values: getValues()
}],
onsubmit: function( e ) {
editor.insertContent('dd');
}
});
}
});
});
})();
function getValues() {
//Set new values to myKeyValueList
tinyMCE.activeEditor.settings.myKeyValueList = [{text: 'newtext', value: 'newvalue'}];
return editor.settings.myKeyValueList;
}
Try changing return statement to
return tinyMCE.activeEditor.settings.myKeyValueList;
variable editor is probably undefined in global scope.
Issue
I just started using Select2 (http://ivaynberg.github.io/select2/) and I am trying to do a basic task.
I have a select box that has, for example, 3 items in it. I want to be able to have the user either select 1 of the 3 results or type in their own result and then eventually, on submit, it will submit whatever value is in the box.
What I've Tried
<input style="width: 200px;" type="hidden" id="foo" />
<script type="text/javascript">
$(document).ready(function () {
$("#foo").select2({
query: function (query) {
var data = { results: [{ text: 'math' }, { text: 'science' }, { text: 'english' }] };
data.results.push({ text: query.term });
query.callback(data);
}
});
});
</script>
The code above allows me to see the 3 results and type in a result myself. But I am unable to get the typed in result to "stick" when I click away, hit enter, or select the result I just typed in. Same goes for the select options, but I am most concerned with the user inputted text.
Here's what it looks like:
The parameter createSearchChoice allows you to do just what you want. Here is an example:
<script type="text/javascript">
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};
}
},
multiple: false,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
</script>
Taken from a closed issue at: https://github.com/ivaynberg/select2/issues/201
Fiddle: http://jsfiddle.net/pHSdP/2/
Also, make sure you add a name to the input, otherwise you won't see the value at server side
<input style="width: 200px;" type="hidden" id="foo" name="foo" />
Just a quick note for anyone else who's having a different data input. In case the console says " this.text is undefined ", make sure you check your text tag, like this:
<script type="text/javascript">
// Data input taken from "label", not "text" like usual
var lstData = [{id: 0, 'label': 'story'},{id: 1, 'label': 'bug'},{id: 2, 'label': 'task'}];
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.label.localeCompare(term)===0; }).length===0) {
return {id:term, 'label':term};
}
},
data: { results: lstData, text: 'label' }
});
</script>
Library you are using is used to filter options in a select box. It doesn't take new input, as per their own documentation:
Select2 is a jQuery based replacement for select boxes.It supports searching, remote data sets, and infinite scrolling of results.
I would suggest you to use jQueryUI Autocomplete or TypeAhead