live search add a href to results - javascript

I have a live search in laravel 7
everything works good
but I cant add (href a tag) to result list
because result show in select option (select2 library) without (a) tag and cant be open in a new page for see result for this keyword
my blade:
<div class="fre-search-wrap">
<select class="livesearch form-control" name="Find Consultants"></select>
</div>
my scripst:
<script type="text/javascript">
$('.livesearch').select2({
placeholder: 'Select Consultants',
ajax: {
url: '/live_search/action',
dataType: 'json',
delay: 550,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
},
cache: true
}
});
the main source was this
https://www.positronx.io/laravel-autocomplete-search-with-select2-example/

Hello guy you can use this to add a tag:
$('.livesearch').select2({
placeholder: 'Select Consultants',
ajax: {
url: '/live_search/action',
dataType: 'json',
delay: 550,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: ""+item.title+"", // a tag
id: item.id
}
})
};
},
cache: true
}
});

Related

select2 is not showing when the map is fullscreen

hey i was trying to show the select2(its backend) on google map and that worked but when the map is full screen then the lists are not showing.i tried by changing the z-index value but is not working.can anybody help me ??
$('document').ready(function() {
$('#Name').select2({
placeholder: "Choose name",
minimumInputLength: 3,
ajax: {
url: 'somthing here ...',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
// console.log(data);
return {
results: data
};
},
cache: true
}
});
});
Right now your select2 div is outside of all div last element of body.
Pass dropdownParent with google map class so the select2 div will inside the that div.
check with the inspect element and then try to use z-index.
$('#Name').select2({
placeholder: "Choose name",
minimumInputLength: 3,
dropdownParent: $('.map'),
ajax: {
url: 'somthing here ...',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
// console.log(data);
return {
results: data
};
},
cache: true
}
});
Check more info : common-problems

javascript make select 2 use url set by outside source

I'm using select2 to pick out games from a database, however, the file I wish it to search from will change depending on what's selected from a dropdown.
How do I get it so select2 always uses the most up to date "picker_url"?
So if I select a certain option from a select box on a page, it changes the "picker_url" (an ajax file to do the search). The problem is, select2 only seems to use the original value.
Here's my current code:
var picker_url = "test1.php";
$(document).on('change', ".category_select", function(e)
{
var id = $(this).val();
if (id == 16)
{
picker_url = "test2.php";
}
});
$(".game_picker").select2({
selectOnClose: true,
width: '100%',
ajax: {
url: picker_url,
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
cache: true,
},
minimumInputLength: 2
});
Found the answer here: https://github.com/select2/select2/issues/1679#issuecomment-280080742
var someCondition
ajax: {
url: function() {
if (someCondition) {
return '/api/1/someFile.json'
} else {
return '/api/1/someOtherFile.json'
}
}
}
I suggest to use dynamic-urls, like the code below:
$('#mySelect2').select2({
ajax: {
url: function (params) {
return '/some/url/' + params.term;
}
}
});
Inside url function you can test other variables than params, like in the following snippet:
$('#category').select2({
placeholder: "Select category...",
width: '100%',
});
$('#category').on('select2:select', function(e) {
var data = e.params.data;
console.log("category", data);
categ = e.params.data.id;
});
var categ = "1";
$('#project').select2({
placeholder: "Select item...",
width: '100%',
ajax: {
type: "GET",
url: function(params) {
console.log("ajax func", params, categ);
var url = 'https://jsonplaceholder.typicode.com/comments?postId=' + categ
return url;
},
cache: true,
processResults: function(data) {
return {
results: $.map(data, function(obj) {
return {
id: obj.id,
text: obj.name
};
})
};
},
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<div class="group">
<select id="category">
<option value="1">cat 1</option>
<option value="2">cat 2</option>
</select>
</div>
<br>
<div class="group">
<select id="project">
<option value=""></option>
</select>
</div>
I would save off your default options and then recreate the select2 whenever you need to by extending your new URL into the default options:
var defaultOptions = {
selectOnClose: true,
width: '100%',
ajax: {
url: "test1.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
cache: true,
minimumInputLength: 2
};
//Use default to create first time
$(".game_picker").select2(defaultOptions);
//On change, recreate
$(document).on('change', ".category_select", function(e)
{
var options = defaultOptions;
if ($(this).val() == 16)
{
//Create a new options object with the url updated
options = $.extend({}, defaultOptions, { url: 'test2.php' });
}
//Create a select2 with the desired options
$(".game_picker").select2(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Set data of a Multiple Select2 element through javascript

I'm loading multiple values into a Select2 element through Javascript, ajax and jquery. While the data is loading properly and can be accessed once loaded, I'm unable to set stored data in the Select2 element.
Edit: I'm using Select2 v3.5.
My code:
HTML:
<input class="jsData" style="width: 100%" id="select2Data"></input>
Javascript:
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
contentType: 'application/json',
url: '<%=Url.Action("GetData","Controller")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
return {
results: $.map(JSON.parse(data), function (item) {
return {
text: item.term,
slug: item.slug,
id: item.Id
}
})
};
}
},
multiple: true
});
So, this creates a Select2 element where I can traverse to and from a database and load data depending on what I've typed. I can also access the data (entered by the user) using the following line:
$('.jsData').select2('val')
The above line returns an array, which I can store in the database. My current objective is to set the stored data back into the Select2 element. Any help in this matter would be most welcome.
Update: A relevant link for what I want to accomplish:
https://select2.github.io/examples.html#programmatic
I want the example of setting multiple elements in Select2. However, the difference would be in the fact that the example in the Select2 documentation brings data at the time of loading the page, while I will be making trips to fetch the data.
The Select2 v3.5.4 docs are a bit confusing around this. I think there's a typo in the docs that's misleading.
First, notice that when I retrieve the data from the remote source I'm returning it as an object in the format of {id: ##, name: NAME}.
The first step is to add the initSelection parameter and pass the function to retrieve the previously selected items.
The next step, where I believe there's a typo, is to define the formatSelection parameter (not the formatResult it states in the docs). This function defines how the previously selected result is displayed. In this case I'm merely showing the name property of the result.
The formatResult parameter defines how newly selected options are displayed. You'll notice formatResult and formatSelection are the same below. I could have reused a single function but felt this was better for demonstration.
$(document).ready(function() {
function formatResult(data) {
return data.name;
};
function formatSelection(data) {
return data.name;
}
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
results: function(data) {
return {
results: $.map(data, function(user) {
return {
name: user.name,
id: user.id
};
})
};
}
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
dataType: "json"
}).done(function(data) {
callback(data);
});
}
},
formatResult: formatResult,
formatSelection: formatSelection,
multiple: true
});
});
Here's the full working example:
$(document).ready(function() {
function formatResult(data) {
return data.name;
};
function formatSelection(data) {
return data.name;
}
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
results: function(data) {
return {
results: $.map(data, function(user) {
return {
name: user.name,
id: user.id
};
})
};
}
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
dataType: "json"
}).done(function(data) {
callback(data);
});
}
},
formatResult: formatResult,
formatSelection: formatSelection,
multiple: true
});
});
.jsData {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>
<input class="jsData" style="width: 100%" id="select2Data" value="10"></input>

Importing JSON based remote data to Select2 using AJAX

The aim is to import data from the Controller side to a Select2 element (with multiselect toggled on). I want the setup to look something like the tags box in Stack Overflow, wherein you can begin typing a tag, select it, and select another one later.
I have been using the Select2 documentation as a reference, however the request isn't being sent to the Controller.
Select2 Documentation
My Code:
$(".jsData").select2({
ajax: {
contentType: 'application/json',
url: '<%=Url.Action("GetDataMethod","RelevantController")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
var datajs = $.map(data, function (obj) {
obj.text = obj.someterm; // desired field,
obj.id = obj.someId;
return obj;
});
return {
results: JSON.parse("[" + datajs.split(",") + "]")
};
}
},
multiple: true
});
I'm relatively new to bringing data dynamically to Select 2, so any help would be most appreciated. Thanks!
UPDATE: Found the solution, posting it here for others.
HTML
<input class="jsData" style="width: 100%" id="select2Data" ></input>
Javascript
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
contentType: 'application/json',
url: '<%=Url.Action("GetData","Controller")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
return {
results: $.map(JSON.parse(data), function (item) {
return {
text: item.term,
slug: item.slug,
id: item.Id
}
})
};
}
},
multiple: true
});

Select2 dropdown menu (ajax,initSelection) error "options.results is not a function"

I am using select2 plugin(ivaynberg.github.io/select2).
I am trying to display a dropdown(select).
Data getting via ajax, for this I create 2 servlets.
Dropdown menu url: '/testPr1/servlet1'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"},{"id":3,"text":"Genre3"},{"id":4,"text":"Genre4"}]
Init data url: '/testPr1/servlet2'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"}]
I create hidden element for select2 (and set init value)
Select film genre from list:
<input type="hidden" id="film_genre_cbox" style="width:600px" value="1,2" />
Then I get started with creating dropdown
var select_config2 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
},
initSelection: function (element, callback) {
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
};
$("#film_genre_cbox").select2(select_config2);
It works well, select exclude Genre1 and Genre2 as init value
But I want to see these two genres as selected elements in input, like this:
And then I tried to init select2 via ajax
var select_config1 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
// alert(id.toString());
if (id !== "") {
$.ajax({
url:'/testPr1/servlet2',
dataType: "json",
type: "GET",
quietMillis: 0,
}).done(function(data) {
alert(data.toString());
return callback(data);
});
} else {
callback([]);
}
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
};
$("#film_genre_cbox").select2(select_config1);
As result I get init selection as want
But when I start to dropdown I get no menu (Genre3,Genre4)
and error “Uncaught TypeError: options.results is not a function”.
Libs that I use
jquery-2.1.4.js
/select2_v3.5/select2.js
select2_v3.5/select2.css
Where is the mistake?

Categories