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 () {
^^^^^^^^
Related
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
});
});
}
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 a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function