how to get value selected in ajax select2 plugin - javascript

html
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
-------------
jquery
$('body').on('click','#Customer_PO',function(e){
id_tosend=$(this).attr("id").toString();
var cust_id=$('#Customer_list').val();
var a=$('#'+id_tosend).select2({
ajax: {
url: 'ajax/report/inspection_report.php?cust_id='+cust_id,
dataType: 'json',
delay: 500,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data
};
},
cache:true
}
});
a.data('select2').dropdown.$dropdown.addClass("test");
$(this).select2('open');
});
i attach plugin of Select2 .When i submitted data in my form ,it shown me empty value . How i get this value to set selected initial value in ajax method.

you can try this
HTML
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
JQUERY
$.ajax({
url: 'url',
type: 'POST',
data: { id: id},
dataType: 'JSON',
success: function (resp) {
if(resp.msg == 'Done'){
$("#Customer_PO option:selected").removeAttr("selected");
$.each(resp.yourListData, function (key, value) {
$("#Customer_PO ").append('<option value="'+value.ID+'">'+value.name+'</option>');
});
$("#Customer_PO ").trigger("change", [true]);
}
},
error: function (e) {
console.log("Line 1204");
console.log(e.responseText);
}
});

Related

Problems with selecting option with loading data with Ajax request with the object select option

I have performed a rest service performed with C # with ajax request in a combo box, this object shows the data of my rest service, this combo box must fill data from many cities and this shows the cities that I perform in the service, but the inconvenience is in the object combo box or select option in html5, whenever I give in the object, it loads the data and I cannot select my city that I want, reloading it, as an infinite loop when I want to select the data Annex code
https://es.stackoverflow.com/questions/279794/problemas-en-mostrar-datos-en-combo-box-en-pantalla-con-petici%c3%b3n-ajax
<div class="form-group has-feedback">
<label>Ciudad</label>
<select class="form-control" data-rel="chosen" id="Ciudad" name="Ciudad" onclick="ValidarExisteCiudad()">
<option/>
<option/>
</select>
</div>
function ValidarExisteCiudad() {
//$("[data-rel='chosen']").chosen();
//var ddlCiudad = $("[data-rel='chosen']");
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option></option>").val(this['Value']).html(this['Text']));
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> CargaCiudad()
{
List<Cuidad> Items = await drHelpPrueba.Cuidad.ToListAsync();
List<SelectListItem> ciudad = new List<SelectListItem>();
for (int i = 0; i < Items.Count; i++)
{
ciudad.Add(new SelectListItem
{
Value = Convert.ToString(Items.ToList()[i].IdCiudad),
Text = Items.ToList()[i].Nombre
});
}
return Json(ciudad);
}
ddlCiudad.append($("").val(this['Value']).html(this['Text']));
undefined
my friend. Because you don't get true data from the response.
Try following this. Hope to help, my friend :))
function ValidarExisteCiudad() {
var ddlCiudad = $("#Ciudad");
ddlCiudad.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: 'GET',
url: "CargaCiudad",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
ddlCiudad.empty().append('<option selected="selected" value="0">Seleccione ...</option>');
$.each(data, function () {
ddlCiudad.append($("<option> </option>").val(this.value).html(this.text)); //Modified this line
});
// After updated data from database you need to trigger chosen:updated.
//$("[data-rel='chosen']").trigger("chosen:updated");
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
existeUsuario = false;
}
});
}

Why Dropdown Selected value pass as a null value to the controller in jQuery

I have a Dropdown created in Html as like this.
<label for="filter">Type:</label>
<select class="filter"
id="secquneceDropdownId">
<option value="" selected>All</option>
<option value="INSEQUENCE">In Sequence</option>
<option value="OUTSEQUENCE">Out Sequence</option>
<option value="RECIPES">Sequence Mapping</option>
</select>
I have tried to send selected value in jQuery as same as the Ajax JSON format. but I always get the null value in the backend.
Both ways are here,
Using jQuery:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.post("/IdeaOfThings/listSequences", {
isDropdownSelected : dropdownSelected
},
function(data, status) {
});
});
});
In Ajax format:
$(document).ready(function () {
$("#secquneceDropdownId").change(function () {
var dropdownSelected = $(this).val();
console.log('dropdownSelected value is' + dropdownSelected);
$.ajax({
type: "POST",
url: '/IdeaOfThings//listSequences',
data: {isDropdownSelected: dropdownSelected},
dataType: "json",
success: function(data){
if(data.success==true){
alert('success');
}else if(data.success==false){
alert('Failed');
}
}
});
});
});
Why I`m getting null value as always.?
Maybe try changing
data: {isDropdownSelected: dropdownSelected}
to
data: {'isDropdownSelected': dropdownSelected}

Get value from autocomplete dropdown

I need to assign value from dropdown to autocomplete textbox ..till Now I have done this
But You can see I can't assign value from Dropdown to textbox ..
I have implemented auto complete feature by a JQuery PlugIn "Prop.js"
this is the code I have created
<link href="~/Content/popr.css" rel="stylesheet" />
<script src="~/Scripts/popr.js"></script>
<script src="~/Scripts/popr.min.js"></script>
<div id="address" >
<label>Country</label>
<table>
<tr>
<td>#Html.TextBox("Country")</td>
<td>
<div class="popr" data-id="demo">^</div>
<div class="popr-box" data-box-id="demo">
</div>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Location/GetAllCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response(data);
}
})
},
appendTo: '#menu-container',
messages: {
noResults: "", results: ""
}
});
$.ajax({
url: "/Location/GetAllCountry",
type: 'POST',
data: { term: "" },
success: function (states) {
var $select = $('div[data-box-id="demo"]');
$.each(states, function (i, state) {
$('<option>', {
value: state
}).html(state).appendTo($select)
.addClass("popr-item");
});
},
error: function (xhr) { alert("Something seems Wrong"); }
});
});
$('.popr').popr();
$('.popr').popr({
'speed': 200,
'mode': 'bottom'
});
I have searched the solution the tried for a click inside div to get selected value
$(".popr-item").click(function (e) {
e.stopPropagation();
});
$(".popr-box").click(function (e) {
e.stopPropagation();
alert("popr-box");
});
this is not working
I tried another plugin "chosen" .. But it fails in cascading dropdown ..I am not in a position to try another plugin ... I strictly want to use by this way
if there is another plugin available , I need to see example with cascading dropdown specifically
I just need selected value from dropdown , How Can I achieve this ?
Add this select option in autocomplete
$("#Country").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Location/GetAllCountry",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response(data);
}
})
},
select: function( event, ui ) {
$( "#Country" ).val( ui.item.label );
return false;
},
appendTo: '#menu-container',
messages: {
noResults: "", results: ""
}
});

How can i make an option selected with jquery-template

I'm using jquery-template and i need make an option selected, according json's value.
Javascript:
$.ajax({
type: 'POST',
url: caminho + '/controller/ctrl_usuario.php',
data: 'acao=buscarUsuarioPorId&idUsuario=' + id,
dataType: 'json',
success: function (response) {
if (response.status == 1) {
//$('.cadastro').append(response.dados);
$("#" + id).loadTemplate(caminho + "cadastro/form-usuario.php", response.dados, {error: function (e) {
console.log(e);
}});
}
},
complete: function () {
//code
}
});
json returned:
"dados":[{"nome":"Maria Silva","l_Sexo":"F"}]"
<div class="wrp-inp">
<label for="genero">GĂȘnero:</label>
<span class="icon-chevron-down"></span>
<select name="genero" id="genero" >
<option value="M" {{if l_Sexo == 'M'}}selected{{/if}}>Male</option>
<option value="F" {{if l_Sexo == 'F'}}selected{{/if}}>Female</option>
</select>
</div>
The sample above didn't work.
Just do:
var value = 'M';
$('select[name="genero"]').val(value);
The complete Solution:
Javascript:
$.ajax({
type: 'POST',
url: caminho + '/controller/ctrl_usuario.php',
data: 'acao=buscarUsuarioPorId&idUsuario=' + id,
dataType: 'json',
success: function (response) {
if (response.status == 1) {
$("#" + id).loadTemplate(caminho + "cadastro/form-usuario.php", response.dados, {error: function (e) {
console.log(e);
}});
var sexo = response.dados[0].l_Sexo;
$("#genero").val(sexo);
}
},
complete: function () {
//code
}
});
HTMl:
<div class="wrp-inp">
<label for="genero">GĂȘnero:</label>
<span class="icon-chevron-down"></span>
<select name="genero" id="genero" >
<option value="M">Masculino</option>
<option value="F">Feminino</option>
</select>
</div>

Select2 allowClear not working with dynamic dropdown list

I have tried a lot of ways to fix this problem.
At a dynamic list loaded via ajax, I can't make allowClear work.
Here is my jsFiddle
HTML:
<select id="first" class="init-select2" data-placeholder="First dropdown" data-allowclear="true">
<option></option>
<option>First option</option>
<option>Second option</option>
</select>
<select id="second" class="init-select2" data-placeholder="Second Dropdown" data-allowclear="true" disabled="disabled">
<option></option>
</select>
Javascript:
$(function() {
$('.init-select2').removeClass('init-select2').each(function(){
if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "true"){
$(this).select2({
allowClear: true
});
} else if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "false") {
$(this).select2({
allowClear: false
});
}
});
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {"json":JSON.stringify({"one":"first","two":"second","three":"third"})},
cache: false,
success: function(data) {
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({ allowClear: true });
});
}
});
});
});
in jsfiddle are already added the select2 javascript and css, please have a look there
Fixed by adding an "<option></option>" to second dropdown each time I change the value of first dropdown. See success handler below:
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"json": JSON.stringify({
"one": "first",
"two": "second",
"three": "third"
})
},
cache: false,
success: function (data) {
options.push("<option></option>");
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({
allowClear: true
});
});
}
});
});
Example of one of my own, as you can see I don't use "option" tags within my loop.
function companyURL() {
if ($.isNumeric($('#supplier_select').val())) {
return company_url + '/' + $('#supplier_select').val() + '/';
} else {
return company_url;
}
}
var results = [];
$('.company_select').select2({
ajax: {
url: function () {
return companyURL();
},
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
results.push({
id: '',
text: 'Select a company'
});
$.each(data, function (index, item) {
results.push({
id: item.company_id,
text: item.company_name
});
});
return {
results: results
};
}
}
});

Categories

Resources