Load dropdown list based on another dropdown selected item - javascript

Load dropdown list based on another dropdown selected item
Here my js :
$("#Ownerstate").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgency").html(procemessage).show();
var url = "/Index/GetAgencyState/";
// Get state code
var Ownerstate = $("#Ownerstate :selected").val();
$.ajax({
url: url,
data: { statecode: Ownerstate },
cache: false,
type: "POST",
success: function (carData) {
if (carData.length > 1) {
$("#OwnerAgency").prop("disabled", false);
}
var select = $("#OwnerAgency");
select.html('');
$.each(carData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Not getting load dropdownlist

Related

set Value of select mobius not working javascript

good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.

Jquery repeater with select2 not working properly

I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})

Select2 dropdown menu (ajax,initSelection) error "options.results is not a function"

I am using select2 plugin(ivaynberg.github.io/select2).
I am trying to display a dropdown(select).
Data getting via ajax, for this I create 2 servlets.
Dropdown menu url: '/testPr1/servlet1'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"},{"id":3,"text":"Genre3"},{"id":4,"text":"Genre4"}]
Init data url: '/testPr1/servlet2'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"}]
I create hidden element for select2 (and set init value)
Select film genre from list:
<input type="hidden" id="film_genre_cbox" style="width:600px" value="1,2" />
Then I get started with creating dropdown
var select_config2 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
},
initSelection: function (element, callback) {
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
};
$("#film_genre_cbox").select2(select_config2);
It works well, select exclude Genre1 and Genre2 as init value
But I want to see these two genres as selected elements in input, like this:
And then I tried to init select2 via ajax
var select_config1 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
// alert(id.toString());
if (id !== "") {
$.ajax({
url:'/testPr1/servlet2',
dataType: "json",
type: "GET",
quietMillis: 0,
}).done(function(data) {
alert(data.toString());
return callback(data);
});
} else {
callback([]);
}
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
};
$("#film_genre_cbox").select2(select_config1);
As result I get init selection as want
But when I start to dropdown I get no menu (Genre3,Genre4)
and error “Uncaught TypeError: options.results is not a function”.
Libs that I use
jquery-2.1.4.js
/select2_v3.5/select2.js
select2_v3.5/select2.css
Where is the mistake?

Select2 doesn't show the initSelection values

the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.

How to populate extra fields with jQuery autocomplete

I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}

Categories