Select2 custom data return from API - jquery-select2

I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []

One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>

$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>

Related

C# razor select2 disable

Is there a way I can set this select2 to be disable read-only if there is a value in option.AgentName? I have add the selectElement.select2 method is there anything I can add to the callback?
Is this the correct way to do this? using self.entry.Agent.AgentName != ""?
View
<div class="form-group sentence-part-container sentence-part ng-scope ui-draggable sentence-part-entry-agent sentence-part-with-select2-single" [class.has-errors]="entry.IsInvalid && entry.IsTouched">
<div class="sentence-part-values">
<div class="sentence-part-values-select2-single">
<select class="form-control" style="width: 300px" [(ngModel)]="entry.Agent.VersionKey">
<option *ngFor="let option of agents" [value]="option.VersionKey">{{option.AgentName}}</option>
</select>
</div>
</div>
</div>
ts file
$selectElement.select2({
initSelection: function(element, callback) {
console.log(self.entry.Agent.AgentName);
if (self.entry.Agent.AgentName != "")
{
console.log('disabled');
$selectElement.prop('disabled', true);
}
callback({ id: self.entry.Agent.VersionKey, text: self.entry.Agent.AgentName });
},
placeholder: "Select an agent"
})
.on("change", (e) => {
self.ngZone.run(() => {
self.entry.Agent.VersionKey = $selectElement.val();
self.entry.AgentVersionKey = self.entry.Agent.VersionKey;
let regimenEntryAgent = this.getRegimenEntryAgentByVersionKey(self.entry.Agent.VersionKey);
if (regimenEntryAgent) {
self.entry.Agent.AgentId = regimenEntryAgent.AgentId;
}
self.onSentenceChange(null);
});
})
.on("select2:close", () => {
self.entry.IsTouched = true;
this.validate();
});
You might try to apply some logic in newData.push() method of Select2.
ajax: {
url: '/DemoController/DemoAction',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
// apply some logic to the corresponding item here
if(item.AgentName == "x"){
}
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.AgentName
});
});
return { results: newData };
},
cache: true
},
Update:
It is recommended that you declare your configuration options by passing in an object when initializing Select2. However, you may also define your configuration options by using the HTML5 data-* attributes.
For the other Select2 options look Options.

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data, params) {
// 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, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

jquery autocomplete with ASP.NET MVC

I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ

Jsp ajax call using jquery

I have this code snippet where I am passing data to another jsp file.
Javascript
$(document).ready(function() {
$("#click").click(function() {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type : "POST",
url : "pageTwo.jsp",
data : "name=" + name + "&age=" + age,
success : function(data) {
$("#response").html(data);
}
});
});
});
HTML
<body>
Name:<input type="text" id="name" name="name">
<br /><br />
Age :<input type="text" id="age" name="age">
<br /><br />
<button id="click">Click Me</button>
<div id="response"></div>
</body>
and in pageTwo.jsp, my code is
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println(name + age);
%>
but this is not working.Is any mistake in my Jquery ?.Can any one please help me?.
$("#click").click(function(e) {
// e.preventDefault();
...
return false;
});
and of course install firebug or use chrome default developer tools (f12). open console and run the code.
$(document).ready(function () {
$("#click").click(function () {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type: "POST",
url: "pageTwo.jsp",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json",
async: false,
success: function (data) {
$("#response").html(data.d);
}
});
});
});

How to Move code from jsfiddle to local system for testing

This similar to Question https://stackoverflow.com/questions/13693170/changed-version-of-knockout-js
I would like move the code from jsfiddle to local system for testing. The code works for adds, checked, delete. But, what it does not do is load the fake data from within the model.js. I have changed /echo/json. to local url. What else do I need to do? Using latest firefox.
model.js >>>>
$(document).ready(function() {
var fakeData = [{
"title": "Wire the money to Panama",
"isDone": true},
{
"title": "Get hair dye, beard trimmer, dark glasses and passport",
"isDone": false},
{
"title": "Book taxi to airport",
"isDone": false},
{
"title": "Arrange for someone to look after the cat",
"isDone": false}];
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.destroy(task) };
self.save = function() {
$.ajax("/ds", {
data: {
json: ko.toJSON({
tasks: this.tasks
})
},
type: "POST",
dataType: 'json',
success: function(result) {
alert(ko.toJSON(result))
}
});
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
$.ajax("/ds", {
data: {
json: ko.toJSON(fakeData)
},
type: "POST",
dataType: 'json',
success: function(data) {
var mappedTasks = $.map(data, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
}
});
}
ko.applyBindings(new TaskListViewModel());
});
ds.html
<script type="text/javascript" src="static/js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="static/js/knockout-2.0.0.js"></script>
<p>
<div class="codeRunner">
<h3>Tasks</h3>
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<ul data-bind="foreach: tasks, visible: tasks().length > 0">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
You have <b data-bind="text: incompleteTasks().length"> </b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - it's beer time!</span>
<button data-bind="click: save">Save</button>
</div>
</p>
<script type="text/javascript" src="static/js/model.js" ></script>
The ajax requests in the fiddle are just mock requests to simulate real-world scenarios, they're not really necessary.. you can use that fake data without any ajax requests. For example change these parts:
self.save = function() {
alert(ko.toJSON({tasks: this.tasks}));
};
//Load initial state from server, convert it to Task instances, then populate self.tasks
var mappedTasks = $.map(fakeData, function(item) {
return new Task(item);
});
self.tasks(mappedTasks);
If you want to use ajax requests to get real data, you'll need to post the data in the format required by your own server API (i.e. not with that 'json' field in the data that is used in jsfiddle's json-echo service API)

Resources