I need to pass value from select2 to javscript. But its not working.
this is my html code
<select class="txtTeamAddDelete form-control" name="itemName"></select>
</div>
<button type="button" class="btnrowAddDelete">Add New Row</button>
This is my javascript select2
<script type="text/javascript">
$('.txtTeamAddDelete').select2({
placeholder: 'Select an item',
ajax: {
url: "{{route('meeting.list-meeting.dataAjax')}}",
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id,
email: item.email
}
})
};
},
cache: true
}
});
</script>
this is js for display select2 data
$(document).ready(function(){
$('.btnrowAddDelete').click(function(){
var txtTeamAddDelete = $('.txtTeamAddDelete').find(':selected').text();
$('.TableAddDelete tbody').append("<tr><td>"+txtTeamAddDelete+"</td><td>"+email+"</td></tr>");
});
});
its working to fetch name data but not email. I want to fetch two data: email & name. i already tried this
var txtTeamAddDelete = $('.txtTeamAddDelete').select2('val',["name", "email"]);
but it return undefined
i want to show it like this. can someone help me. Thanks!
Related
so I use this code to make everything that has the $(".select2") element will process ajax according to the rest of the data sent via html
$(".select2").each(function () {
let element = $(this);
element.select2({
theme: "bootstrap",
placeholder: element.data("placeholder"),
ajax: {
url: element.data("url"),
dataType: 'json',
delay: 100,
cache: true,
data: function (params) { return { q: params.term } },
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
text: item.bank_name, /***** this *******/
id: item.id /***** this *******/
}
})
};
}
},
});
})
I've added element.data ("placeholder") and element.data ("url") in jquery, while how to send it with this html code
<select id="bank_id" name="bank_id"
class="fetch_bank form-control select2"
data-placeholder="Choose Bank"
data-url="/api/bank/fetch">
</select>
sending it ajax will return the following results
{
code: 200
error: false
message: "loaded!"
results: [
{id: 1, bank_name: "AMERICAN EXPRESS BANK LTD"},
{id: 2, bank_name: "ANGLOMAS INTERNASIONAL BANK"},
....
]
}
I have 3 records that return json, to display to select2, the column is as below
Bank(id, bank_name)
School(id, school_name)
Status(id, status)
but the problem is, how do i make 'processResults' dynamic? which I have marked with a comment / ***** this ******* /
While the 3 data has different keys, how do I make the select2 function dynamic?
thanks, I hope someone answers my question :)
I'm using select2 to show ajax results in a dropdown but when I append data to select2 its showing error
TypeError: b is undefined
JS Code
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
term.term contains the value of input text in dropdown search box.
HTML
<select class="myselect" style="width: 50% !important">
<option></option>
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
<option value="KY">Kentucky</option>
</select>
JSON RESPONSE
[{"id":9858,"firstname":"Testing3","status":2,"state":"VA","phone":""},{"id":9857,"firstname":"Testing2","status":2,"state":"VA","phone":""},{"id":9856,"firstname":" david polosky ","status":3,"state":"FL","phone":"(000)000-4141"}]
SELECT2 CDN LINKS
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
PHP SERVERSIDE CODE (LARAVEL)
$searchtext = $request->get('term');
$data = Inspector::latest('id')
->select('id', 'firstname', 'status', 'state', 'phone')
->where('firstname', 'LIKE', '%' . $searchtext . '%')
->get()->toArray();
echo json_encode($data);
Any help is appreciated.
In your ajax configuration you use results you should use processResults
Try this
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
processResults: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
Aamir#, sometimes errors are misleading. If you see from your code, it doesn't have a reference to b at all. I believe that must be an error that is being thrown from a method outside of your code, due to an error in your code.
You might have to set a break point by clicking on the line number on browser console and then check the call stack to find the error in the code.
I'm using Select2 Ajax to apply autocomplete on my html select
this is the select2 code :
<script>
$(function(){
$(".marques-multi").select2({
minimumInputLength: 3,
tags: [],
ajax: {
url: "user/marques",
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return term;
},
processResults: function (data) {
return {
results: data
};
},
transport: function (params, success, failure) {
var $request = $.ajax(params);
$request.then(success);
$request.fail(failure);
return $request;
}
}
});
});
</script>
and this is my html :
<select class="form-control input-sm marques-multi" name="marque"></select>
and this is what the URL : "user/marques" with the data (www.mywebsite.com/user/marques/marques?term=nike) returns :
[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]
when I write as example nik in the select input i see in the console that the requests returns this json bellow with no errors but the select doesn't get fill with this data it stays blank.
If possible, change your data properties on JSON from id_marque and marque_name to id and text instead.
So from:
[
{"id_marque":"50670","marque_name":"NIK HUBER GUITARS"},{"id_marque":"50671","marque_name":"NIKALAS CATLOW"},{"id_marque":"1","marque_name":"NIKE"},{"id_marque":"50672","marque_name":"NIKE"},
{"id_marque":"50673","marque_name":"NIKE"},{"id_marque":"50674","marque_name":"NIKE 6.0"},{"id_marque":"50675","marque_name":"NIKE ACCESSORIES"},{"id_marque":"50676","marque_name":"NIKE ACG"},{"id_marque":"50677","marque_name":"NIKE ACTION SPORTS"},{"id_marque":"50678","marque_name":"NIKE AIR MAX"},{"id_marque":"50679","marque_name":"NIKE BAIN"}
]
To:
[{"id":"50670","text":"NIK HUBER GUITARS"},{"id":"50671","text":"NIKALAS CATLOW"},{"id":"1","text":"NIKE"},{"id":"50672","text":"NIKE"},
{"id":"50673","text":"NIKE"},{"id":"50674","text":"NIKE 6.0"},{"id":"50675","text":"NIKE ACCESSORIES"},{"id":"50676","text":"NIKE ACG"},{"id":"50677","text":"NIKE ACTION SPORTS"},{"id":"50678","text":"NIKE AIR MAX"},{"id":"50679","text":"NIKE BAIN"}];
Fiddle
I'am using select2 version 3.4.6.
Iam having some trouble getting the data to the input field, here's my html:
<div class="col-md-5">
<input id="assetTypes" name="assetTypes" class="form-control input-xlarge" placeholder="" />
</div>
The backend returns te following output:
[{"name":Server,"id":1},{"name":Database,"id":2}]
And the js is as follows:
$("#assetTypes").select2({
ajax: {
url: "/assets/getAssetTypes",
dataType: 'json',
type: "GET",
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: $.map(data, function (obj) {
return {
text: obj.name,
id: obj.id
}
})
};
}
}
});
I don't get any errors in the chrome js console, but as I type, the spinner just keeps spinning without returning any data.
Any suggestions to what the problem might be?
For your map call, change the function declaration from function() to function(obj) and then use:
text: obj.name,
id: obj.id
I am using Select2 3.5.1. With this plugin I can successfully load remote data. However I am here today to ask a question to improve this search. Here is the step-by-step to understand what I would like to do:
Setup a Select2 with remote data loading (using ajax).
Click on the Select2 input and search for something.
The loading will appear and after some seconds you will see a list of results.
Click on one of the results listed - the box of results will then disappear.
If you click again on the search box, the list will be empty and you will need to type some new text again to have a list of results.
Is it possible that when we click again on the search box, that the list of results previously searched re-appear without any ajax call? Then if the user delete a character or change his search criteria it would then trigger the ajax search again.
If it is possible, how would we code that?
I hope my question is clear, please let me know if you have any questions. Thank you.
Here is a very simple code where we do a search that return a list of results. It doesn't really search, but it does return a list when you type something. I am not sure how to use the initSelection that is mentionned in one of the response.
<html>
<head>
<title>
Test page for ajax cache
</title>
<script type='text/javascript' src='../../resources/javascript/jquery/jquery-1.9.1.min.js'></script>
<link type='text/css' href='../../resources/javascript/select2/select2.css' rel='stylesheet' />
<script type='text/javascript' src='../../resources/javascript/select2/select2.js'></script>
<script>
$(document).ready(function(){
$('#select').select2({
ajax: {
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: function(term, page){
return {
autoc: 'country',
term: term
}
},
results: function(data, page){
console.log(data);
return( {results: data.results} );
}
},
placeholder: 'Search something',
minimumInputLength: 3,
width: '333'
});
});
</script>
</head>
<body>
<input type='text' name='inputdata' id='select' />
</body>
</html>
The very simple ajax.php called:
<?php
$results2['more'] = false;
$results2['results'][0] = array('id'=> "1", 'text'=> "California");
$results2['results'][1] = array('id'=> "2", 'text'=> "Canada");
$results2['results'][2] = array('id'=> "2", 'text'=> "Someword");
$results2['results'][3] = array('id'=> "2", 'text'=> "Alberta");
$results2['results'][4] = array('id'=> "2", 'text'=> "New York");
echo json_encode($results2);
I did read your post once again.
I misunderstood you last time.
The solution is here.
$(document).ready(function () {
$('#select').select2({
// this part is responsible for data caching
dataCache: [],
query: function (q) {
var obj = this,
key = q.term,
dataCache = obj.dataCache[key];
//checking is result in cache
if (dataCache) {
q.callback({results: dataCache.results});
} else {
$.ajax({
url: 'ajax.php',
data: {q: q.term},
dataType: 'json',
type: 'POST',
success: function (data) {
//copy data to 'cache'
obj.dataCache[key] = data;
q.callback({results: data.results});
}
})
}
},
placeholder: 'Search something',
width: '333',
minimumInputLength: 3,
});
// this part is responsible for setting last search when select2 is opening
var last_search = '';
$('#select').on('select2-open', function () {
if (last_search) {
$('.select2-search').find('input').val(last_search).trigger('paste');
}
});
$('#select').on('select2-loaded', function () {
last_search = $('.select2-search').find('input').val();
});
});
This will make another ajax call but with the same query string as before. Uses event select2:closing to save last query string and select2:open to insert the string into the search input and trigger input event.
var lastQueryString = '';
jQuery(".my-select2").select2({
minimumInputLength: 2,
placeholder: "Select an option",
ajax: {
url: "/example",
data: function (params) {
var query = {
search: params.term
}
return query;
},
processResults: function (data) {
return {
results: JSON.parse(data)
};
}
}
});
jQuery('.my-select2').on('select2:open', function () {
if (lastQueryString) {
jQuery('.select2-search').find('input').focus().val(lastQueryString).trigger('input');
}
});
jQuery('.my-select2').on('select2:closing', function () {
lastQueryString = jQuery('.select2-search').find('input').val();
});