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);
Related
I have select function using jQuery select2. I have problem with displaying value that has been selected from the previous form.
In my page details, I want to display the selected value that user has choose. The also can update if they want.
How do I show it up as selected based on the id that I have retrieve form the api ${e.tag.id} instead of like this ?
-Red
-Yellow
-New -> selected
-Others
Should have only show New once.
I will get all the value first from my api url then I will append it on the id=tag. If user have not put the tag yet it will display the select tag for them but if the user already inserted the tag previously, value will be displayed on the <select> box area. But I don't want it to show up on the <option> because it will get duplicated.
This is what I have tried
$('#tag').select2({
placeholder: "Select Tag",
allowClear: true
});
const getTagList = () =>{
axios.get(`url`)
.then(function (res) {
if(res.data.status == 'success')
{
if(res.data.result.length > 0)
{
res.data.result.map((e) => {
$('#tag').append(`<option value="${e.tag.id}">${e.tag.title}</option>`);
});
}
}
});
}
if(e.tag.id == '0'){ tagInfo+= ` <option value="" hidden>Select Tag</option>`;}
else { tagInfo+= `<option value="${e.tag.id}" selected >${e.tag.title}</option>`;}
<!-- list tag -->
<div class="row mb-4 align-items-end">
<div class="col-md-10">
<div class="form-group">
<label class="form-label">Tag</label>
<div class="form-control-wrap">
<select class="" name="tag" id="tag">
${tagInfo}
</select>
</div>
</div>
</div>
</div>
I already read the value from the database and show it up on the text. But I don't want it to sit on the if the value is same as in the it should only appears once. Instead it should just shows as selected. But with my current code it appears twice in the list.
I think if you can do it in this way.
=> For Binding Your Select
const getTagList = () =>{
axios.get(`url`)
.then(function (res) {
if(res.data.status == 'success')
{
if(res.data.result.length > 0)
{
res.data.result.map((e) => {
if($("#tag option[value='"${e.tag.id}"']").length==0){
$('#tag').append(`<option value="${e.tag.id}">${e.tag.title}</option>`);
}
});
}
}
});
}
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);
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
I have a select with two options. When changing the select ... I want to filter/autocomplete a different database. Without http://aehlke.github.io/tag-it/ it's working fine and the autocomplete is changing the source ... but not with it. It stays at source_01.php although I see in the console the change of Test Source 01 to Test Source 02. What might causes this?
HTML:
<select id="search_database" class="form-control">
<option value="1" selected="">Source 01</option>
<option value="2">Source 02</option>
</select>
Javascript:
$('#search_database').on('change', function () {
if ( $('#search_database').val() == 1 ) {
console.log('Test Source 01');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_01.php",
...
});
},
...
})
});
} else if ( $('#search_database').val() == 2 ) {
console.log('Test Source 02');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_02.php",
..
});
},
...
})
});
}
});
Your problem is the value not getting picked up by the script when you change the options if you want to pick the value of the changed option you've to do something similar to the below code.
HTML:
<label for="clientSelect" style="margin-left:14px;">Client:</label>
<select name="clientSelect" id="clientSelect" onChange="clientId(this.id)" style="width:180px;"></select>
<input type="text" id="clintId" size="1" hidden>
JavaScript:
function getClient(cId){
//Get the selected ID using this.is in client side HTML then breaks it up using this to get the ID only
var select = document.getElementById("catSelect"),
optionId = select.options[select.selectedIndex],
catId = optionId.id;
I use the hidden text filed to send the selected ID to my PHP then to the database.
I have 3 nested dropdown menus which are dynamically populated from a mysql database and I use Jquery. I want to set a selected value, depending on the entry in my database.
For example:
I have a table that contains many devices. Each device has its storage place (room, shelve, box). Notice: different rooms contain different shelves which contain different boxes, thats why I use a nested dropdown menu.
Next to each device is a button "change".
What I want is that the current storage place of the device is already selected in my dropdown menu.
This is part of my JS functions (got them from another site, I'm very new to JS):
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
mySelect.append($('<option></option>').val(optionValue).html(optionText));
});
}
This is my html code:
Raum:</br></br><select name="manufacturer" id="manufacturer" >
<option value="">Auswahl:</option></select> </br></br>
Regal:</br></br> <select name="printertype" id="printertype" disabled="disabled" >
<option value="">Auswahl:</option></select> </br></br>
Kiste:</br></br><select name="printermodel" id="printermodel" disabled="disabled" >
<option value="">Auswahl:</option></select></br></br>
<div id="loading" style="display: none;"></div>
<div id="output" ></div>
Part of my ajax code:
jQuery().ready(function($){
$('#loading')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
// Ajax Called When Page is Load/Ready (Load Manufacturer)
jQuery.ajax({
url: 'man_list.php',
global: false,
type: "POST",
dataType: "xml",
async: false,
success: populateComp
});
Sorry for that much code, I hope anyone has a good solution for me, which I (the JS noob) can understand :)
You can check your server's response while populating dropdown options
function populateComp(xmlindata) {
var mySelect = $('#manufacturer');
$('#printertype').disabled = false;
$(xmlindata).find("Company").each(function()
{
optionValue=$(this).find("id").text();
optionText =$(this).find("name").text();
var $opt = $('<option> </option>').val(optionValue).html(optionText);
if(/* compare current data with your device here */) $opt.attr("selected", "selected");
mySelect.append($opt);
});
}