I'm using Select2 js library but I can't not put the links into the select options.
Here is my json structure
[{id: 1, title: "Foo", slug: "foo"}]
And my select2 script
$(".search-box").select2({
placeholder: "Enter...",
ajax: {
url: window.location.href + '/search',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
// 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: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
},
cache: true
},
minimumInputLength: 2,
maximumSelectionLength: 6
});
What I expect is when i type and click the title of SELECT OPTION i want the browser go to the post's address (link)
So any help plzzz
You cannot put window.location.href in the URL. Instead, use proper page URL path.
window.location.href is mainly use for page redirection.
Related
I've set up a Select2 instance that queries my database and renders the results via AJAX on an input that the user has access to.
Everything is working but as this is a location selection input for a user and there are districts and municipalities with same names, for example, I want to add a label for each result to identify them either as "District", "Municipality", "Parish", etc. but I'm unable to do so, I've been unable to find any support on this matter on the Internet and the extension itself doesn't seem to be able to do this,
Select2 AJAX Function
$("#location-property-alert-location").select2({
placeholder: "Type the name of the location",
minimumInputLength: 2,
ajax: {
url: '/ajax/search-locations-by-query',
dataType: 'json',
type: "GET",
data: function data(params) {
return {
query: params.term // search term
};
},
processResults: function processResults(response) {
// return{
// results: response.name
// };
response = response.map(function (item) {
// console.log(item);
return {
id: JSON.stringify(item), // json_encode the data so we can pass this through the ID
code: JSON.stringify(item),
test: "hello",
text: item.location_name
};
});
console.log(response);
return {
results: response
};
},
cache: true
}
});
I know Select2 can take additional data parameters such as the code and test parameters I added above but I don't know how exactly I can use these to create elements within the results with each item's category, for example, as portrayed in the screenshot below.
Each item's category is being stringified so I can pass this data through the form's submission either way but I need to identify each item's category on the frontend for the user to be able to differentiate locations,
Anyone has any idea on how to do this?
Cheers
Note: I don't want Select2's label appearance which basically groups options per category.
You can use templateSelection which will format your selection appearance and then change the result according to your json data.
Below is the demo for how this works with random json data.
function formatResult(item) {
//checks if the id present or not
if (!item.id) {
return item.text;
}
//return the format options..
var element = $(`<span>${item.text}<span class="text_small">${item.username}</span></span>'`)
return element;
};
$("#location-property-alert-location").select2({
placeholder: "Type the name of the location",
minimumInputLength: 2,
ajax: {
url: 'https://jsonplaceholder.typicode.com/users', //this is just for demo...
dataType: 'json',
type: "GET",
data: function data(params) {
return {
query: params.term // search term
};
},
processResults: function processResults(response) {
response = response.map(function(item) {
return {
id: JSON.stringify(item.id),
text: item.name,
username: item.username //pass here extra param
};
});
return {
results: response
};
},
cache: true
},
templateResult: formatResult //your selection format
});
.text_small {
font-size: 10px;
color: grey;
margin-left: 10px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select id="location-property-alert-location" style="width:300px"></select>
I'm using Select2 4.0.6-rc.0 from Jquery, the thing is that when I copy and paste a value to be searched and there is only one option, that option is disabled and I can select it nor click it.
In this image I'm expecting only one results cause SF190 belongs to only one user.
But if the search brings more than one result everything is ok, like in this image:
This is the piece of code I'm using to initialize the Select2:
$('.js-data-example-ajax').select2({
width: '100%',
minimumInputLength: 1,
tags: [],
ajax: {
url: '<URL of my action>',
type: "POST",
dataType: "json",
delay: 1000,
data: function (term) {
return {
query: term.term
};
},
processResults: function (data) {
var res = data.map(function (item) {
return { id: item.Id, text: item.Id + ' ' + item.Name };
});
return {
results: res
};
}
}
});
I really don't know whats going on and I can't find any related solutions.
Here's a working codepen based on your example (and another codepen):
$( ".select2" ).select2({
ajax: {
url: "<url>",
dataType: 'json',
delay: 1000,
//type: "POST",
tags: [],
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
var res = data.map(function (item) {
return { id: item.id, text: item.text };
});
return {
results: res
};
},
},
minimumInputLength: 1
});
The only difference is that I removed the request type - I'm pretty sure that you are getting the data here, not posting it :) And if you try to put it back, the filter stops working, albeit in a different way (it returns the full list no matter what you put in the filter), so it might be the source of your problem here.
There is one more thing to consider - are you sure that there is no other code affecting your selectbox? Like something that applies to the .js-data-example-ajax, or any <span> with a single child (that's what a Select2 dropdown part is) etc.
I'm making user profile page on Laravel and using select2 component to filter huge list of items.
I have a ajax-based select2. It's good when you are on /create page, but I need to have selected value in it, when I am on page /edit/1.
$('.search-filter-ajax').select2({
width: '100%',
minimumInputLength: 3,
placeholder: "Search...",
ajax: {
url: '/api/listing/search/',
data: function (term) {
return {
data: term.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
search_from: item.name,
model: 'some_model',
id: item.id
}
})
};
},
dataType: 'json',
type: "GET",
delay: 250,
},
});
I tried to use initSelection function, but no luck, because it creates only select2 text elements, when I need real <option value="1"> something </option> component.
initSelection: function (element, callback) {
var id = $(element).data('select-id');
var text = $(element).data('select-text');
callback({ id: id, text: text });
},
How can I have a valid preselected option in select2 on page load, but still having opportunity to fire ajax call by onChange?
well, you could try to use your own logic to generate slect options like
$.ajax().then((res)=>{
$('#select').html('');
res.data.forEach((item)={$('#select').append($('option').text(item.text).value(item.value);)})
})
I'm trying setup data attributes into select2 options but without success, at this moment i have the following JS code
_properties.$localElement.select2({
ajax: {
url: "url",
type: "POST",
dataType: 'json',
delay: 250,
data: function (params) {
return {
name: params.term, // search term
type: 1
};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
cache: true
},
//define min input length
minimumInputLength: 3,
});
And i want setup a data-source for the selected option value.
I find the solution, looks that resultTemplate dont format the "visual" selected option , need to use templateSelection option:
templateSelection: function(container) {
$(container.element).attr("data-source", container.source);
return container.text;
}
I solved this problem.
$('select').on('select2:select', function (e) {
var data = e.params.data;
$("select option[value=" + data.id + "]").data('source', data.source);
$("select").trigger('change');
});
You can actually use the exact syntax, that you already used. The "source-attribute" just needs to be accessed via data().data.source of the specific select2-option.
So keep your processResults function like you did:
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
source: item.source,
id: item.id
}
})
};
},
and if you want to retrieve the source of the selected option, you can do it like this:
var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;
In fact you can set any variable you want in your processResults function and then select it via data().data.variableName!
I have a select2 dropdown, which is configured for using with remote data. However, my remote datasource provides the search results in a format which seems to be not compatible with select2. The remote data is for example like this:
...
items: [ { value: 1, displayText: "First" }, { value: 2, displayText: "Second" } ]
...
but select2 seems to expect the "id" and "text" fields instead. I've checked all options, and tried to play with formatSelection, formatResult callbacks, but had no success until now, I always get javascript errors about "item.text" being undefined.
I cannot provide a jsFiddle because the web API is not public unfortunately.
Is there a way to configure select2 for using a custom "id" and "text" field? Or what else could be a good workaround for this scenario?
Ok, I figured it out almost immediately after I posted my question. Probably this is not the most efficient way to do this, so I'm still happy if someone has a better answer.
I managed to do a conversion in the results callback in the ajax options.
$("#mySelect").select2({
minimumInputLength: 3,
ajax: {
url: '/',
params: {
type: 'POST',
dataType: 'json',
},
quietMillis: 200,
data: function(term, page) { // page is the one-based page number tracked by Select2
return {
search: term,
pageSize: 10,
pageIndex: page-1,
};
},
results: function(data, page) {
var more = (page * 10) < data.Total; // whether or not there are more results available
return { results: $.map(data.Results, function(e, i) {
return { id: e.value, text: e.displayText, data: e };
}), more: more };
}
}