When I try to pre-select the value with ajax everything except the shown value is working.
Does anyone know where I've made the mistake?
I call the pre_select() function for each <select>.
When I look in to the code, everything is OK, but the label on the page is showing me the ID instead of myTitle. After submitting the form, the data is also ok! I need only the right label...
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
var option = new Option(data.myTitle, data.id, true, true);
mySelect.append(option).trigger('change');
mySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
Here is the HTML output
<select name="form_select[]" class="form-control select2bs4 select2-hidden-accessible" id="form_my_id1" width="100%" required="" data-select2-id="form_stok_id1" tabindex="-1" aria-hidden="true">
<option value="1" selected="" data-select2-id="5">The Title Of Product</option>
</select>
This function has done my job :-)
function pre_select(pre_id, query_id) { //my ID of selection, the query
var mySelect = $('#form_my_id'+pre_id);
$.ajax({
type: 'GET',
dataType:'json',
url: '?search&id='+query_id
}).then(function (data) {
mySelect.select2("trigger", "select", {
data: data
});
});
}
Related
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;
}
});
}
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}
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);
}
});
I have 2 select input fields.
first select input field contains static data.
second select input field needs to be populated depending on first input field selected value.
Below is my code
<select id="filter_type" name="filter_type" class="selectpicker form-control" style="width:30%;">
<option value>Select Filter Type..</option>
<option value="abc">Abc</option>
<option value="def">Def</option>
<option value="ghi">Ghi</option>
<option value="jkl">Jkl</option>
</select>
<select id="search" name="search" class="selectpicker form-control" style="width:70%;" disabled="disabled">
<option value>Select Filter type first..</option>
</select>
Javascript
<script type="text/javascript">
$(document).ready(function()
{
$("#filter_type").change(function()
{
var id=$(this).val();
console.log(id);
var dataString = 'id='+ id;
console.log(dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
console.log(data); // I get error and success function does not execute
}
});
});
});
</script>
Controller
public function get_onchange_data(Request $request)
{
if($id == 'abc')
{
$searches = Abc::select('field_name')->get();
return response(view('/users/Def', compact('searches'))->render());
}
}
I am unable to get returned ajax data.
I get this error:
GET http://localhost:8000/users/abc?id=year&_=1496176229318 500 (Internal Server Error)
I think my check in if condition is wrong. I am considering $id as the value passed from dataString.
I don't know how to do this. Get the data, compare it with if condition and finally return array result of the data.
Edited code
$("#filter_type").change(function()
{
var id=$(this).val();
console.log("1:"+id);
var dataString = '{id:'+ id+'}';
console.log("2:"+dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
console.log("3:"+data);
}
});
});
public function get_search_data(Request $request)
{
return response($request->input('id'));
}
Two/Three issues here:
You haven't defined $id in the context of your method. Access it via your request object $request->input('id');
Don't send your data as a string, send it as an object data: {id: id}
Always return a response. If the statement evaluates to false, the request will not be answered.
I am trying to display city options based on State selected, where states are dynamically loaded according to selected country (country list is static). but the problem is my action page which receives the data from ajax is not receiving any value for state. This is my first try for event binding so please help.
$(document).ready(function() {
$('#country').change(function() {
var value = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"country": value
},
success: function(result) {
var obj = jQuery.parseJSON(result)
$('div#state').html(obj.state);
}
});
});
$('body').on("change", function() {
var value2 = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"state": value2
},
success: function(res) {
var obj2 = jQuery.parseJSON(res)
$('div#city').html(obj2.city);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>Country: </b>
</p>
<select id="country">
<option value="na">Select</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="england">England</option>
</select>
<div id="state"></div>
<div id="city"></div>
You are on the right track but you will need a little change in event binding
to bind events to select element that you have populated after ajax use following. change event is of select.
$(document).ready(function () {
$('body').on("change", "div#state select", function () {
var value2 = $(this).val();
$.ajax({
url: "state_selector_db.php",
method: "post",
data: {
"state": value2
},
success: function (res) {
var obj2 = jQuery.parseJSON(res)
$('div#city').html(obj2.city);
}
});
});
});
Consider this following addition:
$('body').on("change", "#state", function () {
^^^^^^^^