Reputation: 816
I am making a site where I need to add data to a dropdownlist from a C# class that get data from a database.
I have made a site where I can dynamically add a dropdownlist and a text box using jquery:
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><select id="ddlCon" >getCars()</select> <input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<select id="ddlCon"><option></option></select> <input type="text" name="mytext[]" />
</div>
</div>
I have tried using the following jquery, but I can't get it to work:
function getCars() {
$.ajax({
type: "POST",
url: "GS1-128-Palle.aspx/populatePalleList",
data: "{'index':1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var branches = response.d;
$('select').empty();
$.each(branch, function (index, branches) {
$('select').append('<option >' + branch + '</option>');
});
},
failure: function (msg) {
}
});
}
What am I missing?
Upvotes: 2
Views: 81
Reputation: 45
May be this could help you.
success: function (result) {
var markup = "";
if (result.length < 1) {
markup = "<option value='0'>--Nothing to Select--</option>";
} else {
data = result;
markup = "<option value='0'>--Select--</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].ValueId + ">" + data[x].DisplayText + "</option>";
}
}
$("#Dropdownid").html(markup).show();
}
Upvotes: 0
Reputation: 10659
try this:-
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
var dv = $('<div/>'),
select = $('<select/>').appendTo(dv);
dv.append('<input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a>');
$(wrapper).append(dv);
getCars(select);
}
});
and your getCars function:-
function getCars(select) {
$.ajax({
type: "POST",
url: "GS1-128-Palle.aspx/populatePalleList",
data: "{'index':1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var branches = response.d;
$(select).empty();
$.each(branches, function (index, branch) {
$(select).append('<option >' + branch + '</option>');
});
},
failure: function (msg) {
}
});
}
Upvotes: 2