I am trying to develop tree structure using jquery select2 plugin with ajax call that returns json format.I implemented it using struts 2.
my code is as follows
In script section
<script>
$(document).ready(function(){
var id=1;
$('#sub_lessons').select2({
minimumInputLength: 3,
maximumSelectionSize: 1,
multiple: true,
ajax: {
url: 'getData.action?lid='+id,
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function(data, page) {
return {
results: data,
more:false
};
}
},
formatResult: function(data) {
return data.text;
},
formatSelection: function(data) {
return data.text;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
</script>
and in body part
<select id="sub_lessons" class="form-control select2" multiple>
</select>
Here the action is not being called . If The action calls it retuns the following json String
[{"children":[{"children":[{"children":[],"id":15,"text":"algebra 3"}],"id":3,"text":"one one one"}],"id":1,"text":"another ones"},{"children":[{"children":[],"id":14,"text":"ratios"}],"id":6,"text":"lesson one"},{"children":[],"id":8,"text":"one 1"},{"children":[],"id":12,"text":"algebra 2"},{"children":[],"id":13,"text":"lesson 2"},{"children":[],"id":16,"text":"lesson 232"}]
The action is not being called. json format displays in select box something like
1
1.1
1.1.1
1.2
1.2.1
1.2.2
1.3
1.4
Now i want to implement the same using select 2 plug in.
is it possible to possible to do so?
if so please help me to implement this. I could not understand where I am doing wrong.
any help would be appreciated.
It's seems like only the following style ,
http://jsbin.com/wicutoti/20/edit
and i found some topic related to how to customising select2's dropdown
https://groups.google.com/forum/#!msg/select2/S0b-JJJIFYY/il-MYOFdGusJ
it points to not support the tree structure at present
In that thread, about trees: "not yet, something im working on for 4.0". And then: "Support for trees has probably been shelved for 4.0", says Igor and Kevin, the main Select2 developers (it seems, looking at the GitHub stats).
Related
I am using select2 4.0.0 for this project. A lot of the other comments and thoughts on this issue seem be for previous versions of select2, so I decided to post a new question.
I have a select2 on a page that can both create entries in the database and edit entries in the database. The select2 is populated dynamically by ajax after the user types a few letters and they can select a value. This works fine for creating entries when they need to select one.
On the same page, they can click existing entries to display further information and edit the entry in the same form. This also needs to update the select2 element with the correct selection text and update the select element that is backing the select2. Since this is normally done through ajax, the markup doesn't exist normally.
I've tried reading the documentation for select2, but I find it a bit disorganized. Does select2 provide any feature for accomplishing this? Do I need to create and update all the markup manually? I had looked at a dataAdapter, but I'm not sure if that is what I need or not.
HTML:
<select class="form-control" name="entry" id="select_field" data-url="/entry/search"></select>
Code for the select2 element:
$("#select_field").select2({
placeholder: "Search",
minimumInputLength: 2,
allowClear: true,
ajax: {
cache: true,
delay: 250,
method: 'POST',
url: $("#select_field").data('url'),
processResults: function (data, page) {
return {
results: data,
};
},
},
escapeMarkup: function (markup) { return markup; },
templateSelection: function (record) {
if (!record.id) { return record.text; }
return record.title;
},
templateResult: function (record) {
if (record.loading) { return record.text; }
var markup = $("<div>").text(record.title);
return markup.html();
},
});
I'm using Jquery Select2 for my project. I want to keep a default value in a single input field when the page is loaded. I tried this by setting initSelection while I'm initiating the select2 component like this.
$(document).ready(function() {
allowClear: true,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
dataType: 'json',
url: "public/data.php",
data: function (term, page) {
return {
q: term, // search term
component: "map",
all_selected: $("#map-all").hasClass("active"),
parent_value: $("#city").val(),
child_value: ""
};
},
results: 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 remote JSON data
return {results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON("public/data.php?q="+element.val()+"&component=map&all_selected=false&parent_value=&child_value=", null, function(data) {
if ($.isFunction(callback)) {
return callback(data);
}
});
},
formatSelection: format,
formatResult: format,
});
However this does not work as it is should be.
But, when I make multiple: true, as a select2 option, this works perfectly. How do I do this for single hidden field?
Thanks & Regards!
Okay, I solved this by changing the callback from return callback(data); to return callback(data[0]);. I think the reason behind this is since the field is not a multiple field, it only accepts a single object to the callback function.
How set in the drop-down list item selected by the user?
Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?
I have working script which retrieve data for the list.
$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
url: "index.php?modul=getusers",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return { results: data };
}
},
allowClear: true,
formatSelection: function(data) {
return data.text;
}
});
Standard data in ajax call:
{"text":"sample text", "id":"1"}
Input:
<input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid">
I tried to add the following code, but it doesn't work
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.php?modul=getusersfriend&q="+id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.
But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.
You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.
Which is what would happen here:
var id=$(element).val();
Here is a simple example of serializing your form.
PS: Don't really see what bootstrap has to do with anything.
Why is my autocomplete not doing the selectFirst and mustMatch? Do I need a work around for this?
I'm using version 1.8.9 of jQuery.
Here is my setup code:
$(function () {
$("#SelectedSchool").focus().autocomplete({
source: function (request, response) {
$.ajax({
url: "/School/FindShools",
type: "POST", dataType: "json",
data: {
searchText: request.term,
maxResults: 10,
autofill: true,
selectFirst: true,
highlight: true
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.SchoolName,
value: item.SchoolName,
id: item.SchoolId
}
}))
}
})
},
select: function (event, ui) {
SchoolID = ui.item.id.toString();
$("#SelectedSchoolID").val(ui.item.id.toString());
}
});
});
The selectFirst and mustMatch options are gone in the jQuery UI autocomplete plugin. They were available in de bassistance.de autocomplete plugin, which has been deprecated.
Here's a migration guide to the new jQuery UI autocomplete.
Quoted from that guide:
selectFirst: Similar to autoFill (at the top of this list), this option is gone and has now immediate replacement, nor a need for one. The behaviour for selecting values is solid enough to make this option redundant.
mustMatch: Gone, but easy to implement with the select event. Once more, the combobox provides an example for that.
UPDATE
The link to the migration guide isn't working today (2011-04-09). I could fortunately open the site from cache, so I've saved it, zipped it and put it up for anyone to download.
Hope this helps
(2011-04-10: The Migration guide link works again)
I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});