I have an ajax call like so and for each result, I am displaying a dropdown menu like so:
$.each(results, function (key, value) {
html += "<select id='vendorDropdown'><option value='0'>-- Select Vendor --</option></select>"
}
and I am populating the dropdown with another ajax call:
$.ajax({
type: "GET",
url: "/vendorProject/api/connection/getVendors",
dataType: 'json',
cache: false,
success: function (results) {
var vendorDropdown = $("#vendorDropdown");
$.each(results, function (row, value) {
vendorDropdown.append($("<option />").val(value.Vendor_ID).text(value.Vendor_Name));
});
}
});
my problem is that this only populates the first dropdown and not any others, this is due because they all have the same id...what I am trying to do now is make the id unique with the value:
$.each(results, function (key, value) {
html += "<select id='vendorDropdown-" + value +"'><option value='0'>-- Select Vendor --</option></select>"
}
my question is, how would I target these dropdowns with the unique id in the other ajax call ?
Try this,
var cnt = 0;
$.each(results, function (key, value) {
html += "<select id='vendorDropdown-" + value + i +"'><option value='0'>-- Select Vendor --</option></select>"
i++;
}
Related
I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}
I'm kinda new to javascript and ajax.
The page that I'm building will ask user to select from a list. Upon selection, a dropdown will be populated from database, and a default value of that dropdown will be automatically selected.
So far I've been able to populate the dropdown OR automatically select a value. But I can't do them both in succession.
Here's the Javascript snippet that gets called upon selection of an item from a a list:
function onSelectProduct(data, index) {
//part 1: auto populate dropdown
$.ajax({
type: "POST",
async: true,
url: "http://localhost:8007/Webservice.asmx/GetUnitsByProductID",
data: "{productID: " + data.ID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#Details_" + index + "_ConversionID").empty();
$.each(result.d, function (key, val) {
var option = document.createElement('option');
option.text = val.Name;
option.value = val.ID;
$("#Details_" + index + "_ConversionID").append(option);
});
}
});
//part 2: select one of the values
var ddl = document.getElementById("Details_" + index + "_ConversionID");
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == data.StockUnitID){
ddl.options[i].selected = true;
break;
}
}
}
I used
$("#Details_" + index + "_ConversionID").empty(); because I started with all possible options in the dropdown.
If I started with an empty dropdown, ddl.options.length will return 0 for some reason.
From my understanding, the ajax script that I wrote doesn't really change the properties of the dropdown box (ddl.options.length returns either 0 or the full list with or without the ajax operation). If that's true, then what's the right way to populate that dropdown?
Btw I'm using cshtml and .net.
Thanks!
Well you can try using $.when and .done as below:
It will execute your code once the options have been set
$.ajax({
type: "POST",
async: true,
url: "http://localhost:8007/Webservice.asmx/GetUnitsByProductID",
data: "{productID: " + data.ID + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#Details_" + index + "_ConversionID").empty();
$.when(
$.each(result.d, function (key, val) {
var option = document.createElement('option');
option.text = val.Name;
option.value = val.ID;
$("#Details_" + index + "_ConversionID").append(option);
})).done(function(){
//part 2: select one of the values
var ddl = document.getElementById("Details_" + index +"_ConversionID");
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == data.StockUnitID){
ddl.options[i].selected = true;
break;
}
}
});
}
});
I would also like to suggest one thing! Please do not use complete url as your ajax url since when you host the site this will change and http://localhost:8007/ will no longer be available!
You can write following code in Ajax Success :
$("#Details_"+index +"_ConversionID").val('value you want to select');
Thanks
I have various .change jquery methods in order to populate one dropdown using data from another dropdown; this works correctly.
Now, I am having trouble automatically firing these .changes using .trigger("change") in an explicit function. This explicit function should automatically select the correct dropdown items such that after the first trigger's ajax completes, the next should execute etc.
function populate(id, block, chapter) {
$("#Chapters").val(chapter).trigger("change");
$("#Blocks").val(block).trigger("change");
$("#IDs").val(id);
}
Here are the ajax powered methods for populating the respective dropdowns:
(NOTE: I have used async:false to try mitigate my waiting problem; i see that this is most likely not the solution and that the solution may lie somewhere in my explicit function shown above)
$('#Chapters').change(
function () {
var selectedVal = $(this).val();
$.ajax("/Library/GetBlocksByChapter", {
async: false,
data: { "chapterId": selectedVal },
type: "POST",
success:
function (data) {
$("#Blocks").empty().append("<option value='0'>--Select a Block--</option>");
$("#IDs").empty().append("<option value='0'>--Please Select a Block First--</option>");
$.each(data, function (index, value) {
$("#Blocks").append("<option class='form-control' value='" + value["dbid"] + "'>" + value["name"] + "</option>");
}
);
}
});
}
);
$('#Blocks').change(
function () {
var selectedVal = $(this).val();
$.ajax("/Library/GetIDsByBlock", {
async: false,
data: { "blockId": selectedVal },
type: "POST",
success:
function (data) {
$("#IDs").empty();
$.each(data, function (index, value) {
$("#IDs").append("<option class='form-control' value='" + value["dbid"] + "'>" + value["name"] + "</option>");
}
);
}
});
}
);
To make things a bit clearer: I have 3 dropdowns, the first one populates the second one etc.
I have a few buttons on the page that call the method populate(id, block, chapter) in order to auto select the dropdowns; where id,block,chapter are values that are populated in the dropdowns via ajax.
Any help/suggestions would be greatly appreciated :)
Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}
I have the following code in my js file. When i alerted and checked the value of key, its being coming from JSON response, but when i checked my val, its shown as [object object]. So i tried using val.value, the value comes to be undefined.
FYI: I am getting the correct response from my controller through Json, i have checked it, all i want to know is how to populate text value into the dropdown.
$(document).ready(function () {
BindTitle();
});
function BindTitle() {
$.ajax({
"url": "/Admin/GetTitleList/",
"type": "get",
"dataType": "json",
"success": function (data) {
var appenddata;
$.each(data, function (key, val) {
appenddata += "<option value = '" + key + " '>" + val.text + " </option>";
});
$("#TitleId").html(appenddata);
}
});
}
Your way of building dropdown wont work on ie8
try
$.ajax({
url: "/Admin/GetTitleList/",
type: "GET"
success: function (data) {
var items = $('#id of your dropdown');
items.empty();
$.each(data, function (i, drddata) {
items.append($('<option/>', { value: drddata.Value, html: drddata.Text
});
});
},
error: function () {
}
});