jquery Select2 Ajax - How set value (initSelection) - jquery-select2

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.

Related

Choosing Option In Ajax-based Select2 From JS

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();
},
});

select2 default value for single field

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.

jQuery Autocomplete wrong item in text box on select

When a user begins typing in the DRMCompanyName input text box, and autocomplete feature fires that displays both the company name and the company id. When the use clicks on a selection, the company name and id are to be placed into the DRMCompanyName text box and the id in the DRMCompanyId text box just below.
When the json results are returned from the controller, the code in the autocomplete ajax success function populates the drop down list by setting the label to be equal to the value (company name) plus the key (company id) being returned. Likewise the value is set to just the key (company id).
When the user selects a particular item, the label is supposed to go in the DRMCompanyName text box and the value in the DRMCompanyId. However, what winds up happening is the value gets placed in both.
I've scoured my code over and over and cannot find out why the label does not get placed in the DRMCompanyName field.
jQuery
$(function () {
$('#DRMCompanyName').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui);
$('#DRMCompanyName').val(ui.item.label);
$('#DRMCompanyName').text(ui.item.label);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
});
});
Here is a sample screen shot of the ui item from the select function above (the company name is blacked out for privacy). When I click on this particular item in the autocomplete drop down, 200014 gets placed in both the DRMCompanyName and DRMCompanyId fields.
Razor Markup
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyName)
#Html.ValidationMessageFor(model => model.DRMCompanyName)
</div>
<div class="M-editor-label">
#Html.LabelFor(model => model.DRMCompanyId)
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyId, new { maxlength = 10, title = "Start typing company name to activate DRM Company Name lookup. When DRM Company is found, select to fill in DRM Company ID and DRM Company Name fields." })
#Html.ValidationMessageFor(model => model.DRMCompanyId)
</div>
EDIT
After following the suggestion in the answer below, I modified the select function like so:
select: function (event, ui) {
console.log(tempResults[ui.item.value]);
$('#DRMCompanyName').val(tempResults[ui.item.value]);
$('#DRMCompanyName').text(tempResults[ui.item.value]);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
Based on the console.log readout, this accesses the correct value when the user clicks on the autocomplete item. However, it still places the value in both text boxes. What I can't understand, when I select Inspect Element, is that the correct value for DRMCompanyName actually is placed in the HTML, however it does not appear on the screen, only the id or value (as opposed to label).
You are setting label: value + " " + key which will of course add the id in the label.
When you set $('#DRMCompanyName').val(ui.item.label);, it's going to set what you concatenated in the $.map to the value.
One way to do this is to store a temporary result set from the data in the source ajax call to access later. With this temp set, you can now pull any object or key/value from it for use later.
When getting results, store a temporary list of the results.
var tempResults = [];
...
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
tempResults = data;
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
}
Then, on the select, you can now access the stored data and set values:
select: function (event, ui) {
event.preventDefault();
var name = tempResults[ui.item.value].value;
var id = tempResults[ui.item.value].key;
$('#DRMCompanyName').val(name);
$('#DRMCompanyName').text(name);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(id);
$('#DRMCompanyId').text(id);
}
}
EDIT
Forgetting one minor thing! Add this to the beginning of the select: function!
event.preventDefault();
By default, when selecting, the autocomplete will use the ui.item.value to populate the element that it's wired up with. Using event.preventDefault() will prevent the already wired up event handler to be called used within the autocomplete.
event.preventDefault() documentation.

Set the value and display property for jquery's autocomplete source

I've got a remote source which does not return id and value or label. How can I use it as a source for jquery's autocomplete plugin?
You should pass source a function that makes the AJAX request manually, and then performs some post-processing on the returned data:
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data) {
var processedData = $.map(data, function(item) {
return {
value: item._your_property, // Property you want to use for "value"
label: item._another_property // Property you want to use for "label"
}
});
response(processedData);
},
error: function() {
response([]);
}
});
}
Basically, use $.map to turn the array you get back into an array of objects that the autocomplete widget supports.
For a working example, check out the JSONP example on jQueryUI's demo page.

How do I pass an extra parameter to Jquery Autocomplete field?

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'
}
});

Resources