Append selected after ajax call - javascript

I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.
$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
$('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(JSON.stringify(response));
$.each(response.employees.data, function(key, value) {
$('select').append($("<option selected></option>",
//<HERE Selected is not working.
//If I remove selected results load in dropdown
{
value: value.id,
text: value.name
}));
});
$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
$('#editApptModal').modal('show');
});
});
<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>

First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.
var datas = [
{value: 'toto', text: 'Toto'},
{value: 'titi', text: 'Titi'}
];
var options = '';
$.each(datas, function(key, value) {
options += '<option selected>'+value.text+'</option>';
});
$('#select').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select"></select>

You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.
$('#TransportRecord_TransportCarrierID').empty();
$.each(jsonResponse, function (key, item) {
var option = $('<option selected>').text(item.Text).val(item.Value);
$('#TransportRecord_TransportCarrierID').append(option);
});
$('#TransportRecord_TransportCarrierID').selectpicker('refresh');
Html
<select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>

Related

select2 not displaying selected value text added programatically

I have a dropdown created with select2 (v4.0.13 and I can not change it) using AJAX requests on a form where the user can search for things. The page is built with Thymeleaf and when the view is reloaded the dropdown value is lost.
Following the recommendation of the documentation itself when you deal with AJAX values, I have writed this code:
let selectedOption = $('#select2-id');
$.ajax({
type: 'GET',
dataType: 'json',
url: baseAjaxUrl + '/api_endpoint?q=' + myVar,
}).then(function (data) {
if (data.length !== 0) {
let optionValues = data[0];
let option = new Option(optionValues.name, optionValues.id, true, true);
selectedOption.append(option).trigger('change.select2');
selectedOption.trigger({
type: 'select2:select',
params: {data: optionValues}
});
}
});
Now, when the view is reloaded the dropdown has the value but does not show its text. An x appears to remove it and if you hover the mouse over it in the tooltip the text that should be displayed in the dropdown appears.
In the <span> generated by select2 I can see the title attribute with the value that should be displayed:
<span class="select2-selection__rendered" id="select2-anId-container" role="textbox" aria-readonly="true" title="The text that should be displayed">
<span class="select2-selection__clear" title="Remove all items" data-select2-id="20">×</span>
</span>
The select2 is initialised as follows:
$('#select2-id').select2({
ajax: {
url: baseAjaxUrl + '/api_endpoint',
dataType: 'json',
delay: 180,
data: function (parameters) {
return {
q: parameters.term,
page: parameters.page
};
},
processResults: function (data, page) {
return {
results: data
};
}
},
placeholder: {
id: "-1",
text: "Select an item"
},
allowClear: true,
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 5,
templateResult: formatItem,
templateSelection: formatItemSelection,
theme: "bootstrap",
width: myCustomWidth
});
What is the problem or what have I done wrong?
Greetings.
After finding this answer, my problem was that when selecting an option, templateSelection is used. Checking the function I realised that the object I receive has the fields id and name. The object that handles select2 also has the fields id and name but it has another one, text, and this is the one it uses to show the value!
So in the function I use for templateSelection I have to do:
if (data.text === "") {
data.text = data.name;
}
... other stuff ...
return data.text;
Done!

How to load JSON data based on a dropdown input?

I am new to web development and currently experimenting with HTML forms. I am using Chrome to test out how to show JSON data in a div based on a selection from a tag using jQuery, and my code is not working. When I inspect my webpage, it shows the div for the JSON to load, but the data itself is not there after selecting an element from the dropdown menu. Also, I'm using a stylesheet if that makes any difference. Am I going about this incorrectly?
<json>
{
"firstName": "Jason",
"lastName": "Bourne"
},
{
"firstName": "John",
"lastName": "McClane"
}
<html>
<div id="names">
<select id ="drop-list">
<option value="" disabled="disabled" selected="selected">--Select A Name--</option>
<option>Jason Bourne</option>
<option>John McClane</option>
</select>
</div>
<javascript>
$(function() {
let names = $('#names');
dropList.on('select', getDataViaAjax);
function getDataViaAjax(evnt) {
let request = $.ajax({
method: 'GET',
url: 'people.json',
dataType: 'json',
});
request.done(function(data) {
console.log(data);
let dropList = $('#drop-list');
for (let person of data) {
let newParagraph = $('<p>');
newParagraph.text(person.firstName + ' last name ' + person.lastName);
dropList.append(newParagraph);
}
});
request.fail(function(response) {
console.log('ERROR:' + response.statusText);
});
}
});
I used to use this structure, I thinks its simple but efective, hope it works:
//in your html
<form>
<select id="filterAgendas">
</select>
</form>
//In app,js
$.ajax({
url: 'YourJsonFileLocation',
type: 'GET',
success: function(response) {
console.log(response);
const list = JSON.parse(response);
let filter = '';
list.forEach(list => {
filter += `<option value="${list.id}"> ${list.name}</option>`
});
$('#filterAgendas').html(filter);
}
});
//your json file
{
{
id: 1,
name: name1
},
{
id: 2,
name: name2
},
}

How to prevent from data looping in jQuery Ajax?

This is regarding assigning multiple user using Select2 plugin, Ajax and API. The situation, I have a function that contain of 2 Ajax with different pointed URL. Currently, I have pre-selected user that stored in DB. The selection is using Select2 in a Modal. So what is happen now when Modal is opened, 1st Ajax will load URL /all_user to display all user in DB. After that 2nd Ajax will load URL /activity to get and load information for other fields in the same Modal. Both URLs are running in parallel.
URL /all_user successful to display all user. URL /activity also successful to display pre-selected user. However, when I close the Modal and re-open back the same Modal without refresh page, it will definitely load the same function that contain 2 Ajax as mentioned above.
FYI, in /activity I have doing a function to convert from String to Array since I received in String from DB, so need to convert before displaying in Select.
So the problem is both are the data will be duplicate 2x, when I close and re-open, it will duplicate 3x. How to prevent from the duplication?
Below are the pre-selected Select2 in /activity.
Below are the /all_user that successfully display all user
So when Modal is close and re-open back, duplication happen.
HTML
<select type="text" class="form-control mySelect" id="editOwner" name="editOwner" multiple="multiple"></select>
SELECT2 INIT
var mySelect = $('.mySelect').select2({
allowClear: true,
placeholder: "Search Owner...",
minimumResultsForSearch: -1,
width: 600,
});
JS
<span onclick='editOwner(""+value3.l3_id+"")'></span>
function editOwner(id){
activity_id = id;
$.ajax ({
url: '/all_user',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: 'data',
success: function(response){
for (var i = 0; i < response.data.length; i++) {
$("#editOwner").append($("<option>", {
response: response.data[i].fullname,
text: response.data[i].fullname
}));
}
}
});
$.ajax({
url : '/activity',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: {task_id: activity_id}},
success: function(response){
if (response.status == "Success"){
$("#editOwner").val(response.data[0]["task_owner"]).attr("readonly",false);
$(response.data).each(function(key,value){
var owners = value.task_owner.split(',');
$(owners).each(function(k,v){
$("#editOwner").append($("<option selected>", {
response: v,
text: v
}));
});
$("#editOwner").val(owners).trigger("change");
});
}
else {}
},
error: function(e){}
});
$('#editOwnerModal').modal('show');
}
This is because you are calling:
editOwner(id);
on the click event of your your span that contains your select with the ID of #editOwner.
Like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
}
$("#cars").on
(
"click",
addCar
);
</script>
</body>
Every time you open and close the select element with the ID of #editOwner your appending a new option to the select element. You can easily fix this by adding:
$("#editOwner").unbind();
Like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
// Add this to remove the onclick events for #cars so it will only run one time.
$("#cars").unbind();
}
$("#cars").on
(
"click",
addCar
);
</script>
</body>
Or better yet you could only have the function run one time by not calling it with a onclick event at all like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
}
</script>
<script type="text/javascript">
addCar();
</script>
</body>
Unless there is a reason you need to call your ajax with a onclick event you really shouldn't, but if you need to you should call $("#editOwner").unbind(); at the end of editOwner(id); like this:
Edit: Saw that you were calling editOwner(id) with a span that had a onclick event. Just add an ID to that and call $("#mySpan").prop("onclick", null).off("click");
<span id="#mySpan" onclick='editOwner(""+value3.l3_id+"")'></span>
function editOwner(id){
activity_id = id;
$.ajax ({
url: '/all_user',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: 'data',
success: function(response){
for (var i = 0; i < response.data.length; i++) {
$("#editOwner").append($("<option>", {
response: response.data[i].fullname,
text: response.data[i].fullname
}));
}
}
});
$.ajax({
url : '/activity',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: {task_id: activity_id}},
success: function(response){
if (response.status == "Success"){
$("#editOwner").val(response.data[0]["task_owner"]).attr("readonly",false);
$(response.data).each(function(key,value){
var owners = value.task_owner.split(',');
$(owners).each(function(k,v){
$("#editOwner").append($("<option selected>", {
response: v,
text: v
}));
});
$("#editOwner").val(owners).trigger("change");
});
}
else {}
},
error: function(e){}
});
$('#editOwnerModal').modal('show');
// Try adding this.
//$("#editOwner").unbind();
// Or this if you want to use onclick as an attribute.
$("#mySpan").prop("onclick", null).off("click");
}

select2 set option attributes manually for each option

i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?
Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link

How to set Select2 value using initSelection?

I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.
Here is my script:
$("#sub_lessons").select2({
maximumSelectionSize: 1,
placeholder: "Select Sublessons",
allowClear: true,
multiple:true,
ajax: {
url: "getData.action?lid="+lessonid,
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
My html snippet:
<input type="hidden" id="sub_lessons" style="width:300px"/>
When we clicking on the select2 box the data is loading perfectly,
but I have the function like setValue() when button is clicked.
<input type="button" onclick="setValue(1)"/>
And my function is:
function setValue(no)
{
$('#sub_lessons').select2('val',no);
}
But the value is not being set. I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.
any help would be appreciated.
try something like this
$('#sub_lessons').select2('val','no');
I try this; work for me. You should add this to initSelection select2:
initSelection: function (element, callback) {
var id = $(element).val();
$.ajax("url/" + id, {
dataType: "json"
}).done(function (data) {
var newOption = new Option(data.title, data.id, true, true);
$('#sub_lessons').append(newOption).trigger('change');
callback({"text": data.title, "id": data.id});
});
},

Categories