Populate select2 dropdown dynamically - javascript

I am using select2 version 3.5.4.
I want to have two select2 dropdowns side by side. When page loads first time one select2 dropdown has data whereas second select2 dropdown is empty. Once user clicks on an entry/option in the first select2 dropdown an ajax call should be made to the server and second select2 dropdown should be populated with ajax response data. I am not being able to achieve it. Whenever i try to populate second dropdown I get errorrs like,
Option 'data' is not allowed for Select2 when attached to a <select> element
Option 'ajax' is not allowed for Select2 when attached to a <select> element
My code is something like,
HTML:-
<div class="form-group">
<label class="col-md-4 control-label" for="folderSelect">Files & Folders</label>
<div class="col-md-5">
<div class="select2-wrapper">
<select class="form-control select2" id="folderSelect" name="folderSelect">
<option></option>
<option th:each="folder : ${folders}" th:value="${folder}" th:text="${folder}"/>
</select>
</div>
</div>
<div class="col-md-5">
<div class="select2-wrapper">
<select class="form-control select2" id="fileSelect" name="fileSelect">
<option></option>
<option th:each="file: ${files}" th:value="${file}" th:text="${file}"/>
</select>
</div>
</div>
</div>
JS:-
$('#folderSelect').on("select2-selecting", function(e) {
var value = $(e.currentTarget).find("option:selected").val();
var data = null;
$.ajax({url: "test?value=" + value, success: function(result){
data = result;
return result;
}});
$("#fileSelect").select2({
/* ajax: { // Tried but didn't work
dataType: 'json',
url: 'test',
results: function (data) {
return {results: data};
}
}*/
/*data: function() { //Tried but didn't work
$.ajax({url: "test", success: function(data){
return data;
}});
}*/
});
//Tried but didn't work <br>
$("#fileSelect").select2('destroy').empty().select2({data: data});
});

follow this
$("#fileSelect").empty();
$("#fileSelect").select2({data: data});
It worked well in my case

Related

How to add dynamic selected option to a dynamically populated select list?

I'm trying to set the selected option text for a select menu to be whatever location is - this parameter has been passed into the updateDepartment function dynamically from a previous PHP request.
The AJAX function that follows calls to another PHP file to dynamically populate the #editDepartmentLocation select menu with a list of text/value option pairs. One of the names in this list will always match whatever location parameter is passed into the function.
I'm able to set the value of #editDepartmentName to the name parameter as this is just a text input, however when I try to add $("#editDepartmentName").val(location) this does not work and the selected option just defaults to the item at the top of the list, even though the value of location is present in the list.
Is there a way to get around this?
Thanks for any help.
JS:
function updateDepartment(name, id, location) {
$.ajax({
url: "libs/php/getLocation.php",
type: 'GET',
dataType: 'json',
success: function (result) {
console.log(result);
if (result.status.name == "ok") {
$.each(result.data, i => {
$('#editDepartmentLocation').append($("<option>", {
text: result.data[i].name,
value: result.data[i].id,
}));
});
};
},
error: function (error) {
console.log(error);
}
});
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
HTML:
<div class="form-group">
<label for="name">Name:</label>
<input type="text" value="" class="form-control" id="editDepartmentName" required>
</div>
<br>
<div class="form-group">
<label for="location">Location:</label>
<select class="form-control custom-select" id="editDepartmentLocation" required>
</select>
</div>
Ajax is async, so "editDepartmentLocation" is most likely not populated yet.
Try moving:
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
Inside the success function. Or do a comparison like:
var option = $("<option>", {
text: result.data[i].name,
value: result.data[i].id,
});
if (result.data[i].id == location){
option.attr("selected", "selected");
}
$('#editDepartmentLocation').append(option);

Appending options to select element doesn't work - MaterializeCSS

I want to update a select options according to date that the user picks. For that I tried using ajax request to get data and append the data received to a select element as options. There's nothing wrong with the json object that's received as I tried logging data to console and it gives the data I ant. But hen I try to append it to select element the options do not get appended.
JavaScript code
$.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
html code
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
function f1(){ $.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
}
var data ={
"sessions" : [{"value":"value 1","text":"Option 1"},
{"value":"value 2","text":"Option 2"},
{"value":"value 3","text":"Option 3"},
{"value":"value 4","text":"Option 4"},
{"value":"value 5","text":"Option 5"}]
}
function fillSelect(){
var sessionList=data.sessions;
$('#session12').empty();
var msg='';
console.log(sessionList.length);
for(i=0;i<sessionList.length;i++){
var bean=sessionList[i];
msg+='<option value="'+bean.value+'">'+bean.text+'</option>';
}
$('#session12').html(msg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session12" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<button type="button" onclick="fillSelect()"> click to fill</button>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
</div>
If response of async request you are getting in data is similar to what i have written in data variable in snippet then my way of generating the option will work just fine. If response you are getting is exactly same as i have shown in data(by that i mean structure of the variable) then you can simply replace all your code in ajax function with my code in fillSelect function

Using ng-disabled with input select2

I'm trying to enable a select2 field only when another combobox is selected. This works fine with textbox, normal input or even simple select elements, but when I try to use ng-disabled with a select2 that uses an Ajax call, it doesn't work.
Here is part of my code:
<section class="col col-sm-4">
<label class="label" data-localize="Tipo de Participante"></label>
<select id="select_tipo_participante" name="select_tipo_participante" ng-model="filtros.F_ID_TIPO_PARTICIPANTE.Valor"
class="select2" data-placeholder="Selecione..."
ng-disabled="filtros.F_ID_USUARIO.Valor == null">
<option value="null" data-localize="Selecione uma opção"></option>
<option ng-repeat="tipo in dados_listas.tipos_participante" value="{{tipo.ID_TIPO_PARTICIPANTE}}">
{{tipo.NM_TIPO_PARTICIPANTE}}
</option>
</select>
</section>
<section class="col col-sm-4">
<label class="label" data-localize="Novo Usuário"></label>
<input name="select_novo_usuario" id="select_novo_usuario" ng-model="filtros.F_ID_USUARIO.Valor" ng-disabled="filtros.F_ID_TIPO_PARTICIPANTE.Valor == null"/>
</section>
<section class="col col-sm-12">
<label class="label" data-localize="Justificativa"></label>
<textarea rows="3" class="form-control" name="justificativa_redesignacao" ng-model="DS_JUSTIFICATIVA" ng-disabled="filtros.F_ID_TIPO_PARTICIPANTE.Valor == null"></textarea>
I want to keep the second element (id="select_novo_usuario") disabled until the previous one is selected.
The textarea using ng-disabled works just fine.
Here is my ajax call:
$("#select_novo_usuario").select2({
minimumInputLength: 4,
allowClear: true,
placeholder: localize.localizeText('tooltip_select_interessado'),
ajax: {
url: BACKEND_URL + 'usuario_interessado',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
var filter = 'NM_USUARIO,like,' + term;
return {
filters: filter,
filter_id_interessado: 'ID_USUARIO,notin,teste.teste'
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.NM_USUARIO,
slug: item.NM_USUARIO,
id: item.ID_USUARIO
}
})
};
},
},
});
$("#select_novo_usuario").on("select2-selecting", function(e) {
$timeout(function(){
$scope.$evalAsync(function() {
$scope.filtros.F_ID_USUARIO.Valor = e.val;
});
});
});
How can I get it working?
It appears you have it set up correctly.
Try removing ng-disabled="filtros.F_ID_USUARIO.Valor == null on the select
They are disabling each other, it appears.
If I read your code correctly, the input is not populated until something is selected, correct? Since they appear to be disabling each other, it seems neither one should be enabled.
If the select is untouched, it should be set to null. Both your ng-disabled values on your input and textarea should be returning null. Here is a plunker demonstrating that:
Plunker
Both the input and textarea are disabled until you select an item in the select.
I couldn't be able to get it working using ng-disabled, so I did it in the my .js file, making the select I want to disable respond to the $watch of the previous one.
Here is my code as a sampe:
$scope.$watch('filtros.F_ID_TIPO_PARTICIPANTE.Valor', function(newVal, oldVal, scope) {
if(newVal != null) {
$('#select_novo_usuario').select2("enable", true);
$('#select_novo_usuario').select2("val", "");
}
$('#select_novo_usuario').select2("enable", false);
$('#select_novo_usuario').select2("val", "");});
ng-disabled not seem working with Select2
try this one :
//As of Select2 4.1, they've removed support for .enable
$("select").prop("disabled", true);
// instead of $("select").enable(false);

Setting multiple id in option

Hello i am making option to choose among few ips and as its auto generated with php all option id="userip" is same. I face problem when i choose 2nd, 3rd or even 4th it auto take first ip which is 127.0.0.1 even if in option i choose ip 127.0.2.2 or any other.
I wanted to solve this so wanted to know best way to do it.
<div class="row"> Choose ip:
<select name="search">
<option id="userip">127.0.0.1</option>
<option id="userip">127.0.2.2</option>
<option id="userip">127.3.3.3</option>
<option id="userip">127.0.4.4</option>
</select>
<input class="adm" type="button" onclick="getuser()" value="Get Result">
</div>
Here is my js
function getuser() {
var e = $("#userip").val();
$("#showuser").html("")
$.ajax({
url: "adm.php",
type: "post",
data: "action=getuser&search="+e+"",
dataType: "json",
success: function (e) {
// do something
},
error: function () {}
})
}
ID must be unique at the page:
<div class="row"> Choose ip:
<select name="search" id="userip">
<option>127.0.0.1</option>
<option>127.0.2.2</option>
<option>127.3.3.3</option>
<option>127.0.4.4</option>
</select>
<input class="adm" type="button" onclick="getuser()" value="Get Result">
</div>
And for select option value, use child selector. See jquery official documentation
var e = $("#userip option:selected").text();
Or
var e = $("#userip").val();
just fetch the value of the search field. you can also use the callback onchange.
HTML code
<div class="row"> Choose ip:
<select name="search" id="search" onchange="getuser()">
<option id="userip">127.0.0.1</option>
<option id="userip">127.0.2.2</option>
<option id="userip">127.3.3.3</option>
<option id="userip">127.0.4.4</option>
</select>
</div>
JS code
function getuser() {
var e = $("#search").val();
$("#showuser").html("")
$.ajax({
url: "adm.php",
type: "post",
data: "action=getuser&search="+e+"",
dataType: "json",
success: function (e) {
// do something
},
error: function () {}
})
}

Send 3 variables via json not sending properly

I have 3 dropdowns that are created via javascript, they call an 'updateTable' function when a choice gets made.
Ultimately I am trying to 'filter' a table of data depending on choices made in the dropdowns. If the user just picks one of the dropdowns I want the other choices to submit at the same time (just with empty data if they are not selected, or the currently selected choice if they had already chosen them).
My updateTables function looks like this:
function updateTables (creativeVal,stationVal,verticalVal)
{
//-----------------------------------------------------------------------
//Send the filter criteria
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: {"creative": creativeVal, "station": stationVal, "vertical": verticalVal}, //insert url arguments here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
$('#results').empty();
updateTableRows(response);
} //end of on success
}); //End Ajax call
}; //End Creative Function
My dropdowns look like this:
<!--DROPDOWNS-->
<div id="dropdowns">
<div id="creativesel">
Creative -
<select name="creative-select" id="creative-select" onChange ="updateTables(this.value);">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="stationsel">
Station -
<select name="station-select" id="station-select" onChange ="updateTables(this.value)">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="verticalsel">
Vertical -
<select name="vertical-select" id="vertical-select" onChange ="updateTables(this.value)">
<option value="" selected="selected">All</option>
</select>
</div>
</div> <!--Dropdowns ending-->
No matter which dropdown is selected - the request goes through appending ?creative=whatever_the_user_selected_from_any_of_the_3_dropdowns
Ultimately I want it append something like ?creative=whatever_selection&vertical=whatever_selection&station=whatever_selection so I can get the data on the other end and do what I need to with it.
Am I sending the json request improperly?
How about something like this: http://jsfiddle.net/joeframbach/2XBVv/
I've moved the onchange event to jquery where it belongs, and am pulling all the values from all dropdowns rather than just the one that changed.
html:
<!--DROPDOWNS-->
<div id="dropdowns">
<div id="creativesel">
Creative -
<select name="creative-select" id="creative-select">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="stationsel">
Station -
<select name="station-select" id="station-select">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="verticalsel">
Vertical -
<select name="vertical-select" id="vertical-select">
<option value="" selected="selected">All</option>
</select>
</div>
</div> <!--Dropdowns ending-->
javascript:
$(function() {
$('#dropdowns select').change(function() {
//-----------------------------------------------------------------------
//Send the filter criteria
//-----------------------------------------------------------------------
$.ajax({
url: '/echo/json', //the script to call to get data
data: {"creative": $('#creative-select').val(), "station": $('#station-select').val(), "vertical": $('#vertical-select').val()}, //insert url arguments here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
$('#results').empty();
console.log(response);
} //end of on success
}); //End Ajax call
}); //End Creative Function
});
Add the values for the other dropdowns into your onchange call.
updateTables($('#creative-select').val(), $('#station-select').val(), $('#vertical-select').val())
Alternatively, don't pass the parameters in your onChange method and get the values in the updateTable function.

Categories

Resources