Adding additional options to select using ajax - javascript

Im trying to add additional options to a dropdownlist using ajax in JQM. The first option is a static disabled selected and hidden option. The other options are extracted from a webservice using ajax. The dropdownlist itself is inside a popup window.
This is my code:
<div data-role="popup" id="puIceCream"><div>
<center>Select Flavor:</center>
<select id="ddlFlavorsIC">
<option value="" disabled selected hidden>Please Choose...</option>
<!--Flavors are added here-->
</select>
</div>
And the JS code is below:
$("#puIceCream").on("popupafteropen", function (event) {
if (!$("#ddlFlavorsIC option").length) {
WebServiceURL = "IceWS.asmx";
$.support.cors = true;
$.ajax({
url: WebServiceURL + "/GetFlavors",
dataType: "json",
type: "get",
data: "{ }",
contentType: "application/json; charset=utf-8",
error: function (err) {
alert("error: " + JSON.stringify(err));
},
success: function (data) {
var size = data["d"].length;
for (var i = 0 ; i < size; i++) {
$("#ddlFlavorsIC").append("<option>" + ((String)(data["d"][i].value)) + "</option>");
}
}
});
}
});
If I remove the static hidden option on the markup it works fine, but for some reason it doesn't work with it. why is that?
Thanks in advance!

Change
if (!$("#ddlFlavorsIC option").length) {
to
if ($("#ddlFlavorsIC option").length < 2){
Your code only adds flavors if there are zero options in the dropdown, so your one static option causes you not to enter the IF statement.
DEMO

Related

JQuery Editable Select with Data From Database

Any one could help on this case, I have a select tag in which the data is loading from the SQL database using Ajax POST method.
My code is below but it's not working correctly but not displaying any errors also. I am using editable select for achieving this. Any helps will be appreciated.
LINKS
<link rel="stylesheet" href="https:rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" />
<script src="https://rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
AJAX
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
// url: "SerialNumberCapture.aspx/GetAllCompanyDetails",
url: "ViewSerialNumbers.aspx/ViewGetAllTransactionID",
data: "{CompanyCode:'" + companycode + "',TransactionType:'" + transype + "'}",
dataType: "json",
success: function (data) {
//$('#ddlViewTransactionType option:not(:first)').remove();
$("#ddltransactionId").empty().append("<option value='0'>Select</option>");
//$("#ddltransactionId").empty();
$.each(data.d, function (key, value) {
$("#ddltransactionId").append($("<option></option>").val(value.TransId).html(value.TransId));
});
$('#ddltransactionId').editableSelect();
},
error: function (result) {
alert("Failed: " + result.status + ": " + result.responseText);
}
});
I think the issue is caused by the line <b> $('#ddltransactionId').editableSelect();</b> You cannot write to an html tag this way in JavaScript. Here you should just call $('#ddltransactionId').editableSelect(); instead.
For those who may had face this issue, I am posting a workaround that i have done to fix this issue. It support only in HTML5
<input type="text" list="ddltransactionId" id="txtTransactionId" />
<datalist id="ddltransactionId">
<option value="0">Select</option>
</datalist>
Thanks.
i had the same problem here is how you have to do it
$.getJSON("http://localhost:34168/api/machine/getall", function (data) {
$("#modal_machine_name_select").html('');
$.each(data, function () {
console.log(data);
var dt = this;
$('#modal_machine_name_select').editableSelect('add', function () {
$(this).attr('value', dt.Machine_id);
$(this).text(dt.Machine_Name);
});
check the documentation in here => https://github.com/indrimuska/jquery-editable-select

How to clear the text of a linked dropdown (selectpicker) using javascript?

I have the following code and it works well in JSfiddle, but it doesn't work properly on my web page.
On this page, I have dropdown "B" which is populated based on the selected item in dropdown "A". In case of changing "A" items, values of the second dropdown changed correctly but its default text remains unchanged until I change the selected item in the second dropdown manually.
code:
function get_child() {
$("#child").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("Get_child", "Home")',
dataType: 'json',
data: { Name: $("#parent").val() },
success: function (states) {
$("#child").append('<option value="0" selected="selected"> </option>');
$.each(states, function (i, state) {
$("#child").append('<option value="' + state.Text + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
}
});};

Checkbox not refreshing in jquery

I am facing an issue as below.
I have two drop-down, first one is single drop down select, second one is multi select drop-down checkbox. Second one shows the result based on the first drop-down value.
While select the first drop-down, I get the values for second drop-down to show(Values Show in Inspect element) but not in drop down.
Please find the below code for further reference.
abc.html
<select name="list_usergroup[]" multiple id="list_usergroup" >
<option value=""> Select User Group </option>
</select>
mg.js
org_uuid = $('#list_organization').val();
$.ajax({
url: appGetSecureURL("/api/web/getorgug/" + org_uuid),
type: "GET",
dataType: "json",
jsonpCallback: 'jsonCallback',
beforeSend : function(){
loaderOn();
},
success: function(data) {
// Display Usergroups
if (0 == data.ug_total) {
$("#list_usergroup").html('<option value="">No Usergroup.</option>');
}
else {
$("#list_usergroup").html("");
$("#list_usergroup").html('<option value="">Select Usergroup</option>');
for (rowData in data.usergroups)
{
var optionData = '<option data = "'+ data.usergroups[rowData] +'" value="'+ rowData+'">' + data.usergroups[rowData]+'</option>';
$('#list_usergroup').val("");
$('#list_usergroup').multiselect('refresh');
$('#list_usergroup').multiselect('reset');
$("#list_usergroup").append(optionData);
}
//$('#list_usergroup').multiselect('reset');
$("#list_usergroup").multiselect({
columns: 1,
placeholder: 'Select Usergroups',
search: true,
selectAll: true,
onLoad: function() {
}
});
$("#list_usergroup").val(Value);
}
loaderOff();
},
error: function(data, b, c) {
appLog.debug("Display Usergroup error Status " + data.status + ": " + data.statusText)
}
})
I am using https://github.com/nobleclem/jQuery-MultiSelect plugin
Thanks in advance.
To Enable Multiselect with refresh data. you have to re-initialise Multiselect.
$('#list_usergroup').multiselect('destroy'); // tell widget to clear itself
$('#list_usergroup').multiselect(); // re-initialize the widget

Ajax Populated Dropdown Taking Two Clicks

My web page is an internal DB Move Tool for my company. I have a section for source and for target.
I have radio buttons for host and port, and a dropdown for database name. When host and port are set, I have a click event capture on the dropdown that sends an ajax request to a php page that queries for the databases on that instance and populates the dropdown options(this is for the target dropdown):
$("#targetDrop").one("click",function() {
ajaxTarget();
});
function ajaxTarget() {
$.ajax({
url: './dbLookup.php',
type: 'POST',
dataType: "json",
data: {
host: $("#targetHost:checked").val(),
port: $("#targetPort:checked").val()
}
})
.done(function(result) {
console.log("Setting Result");
for (i=0; i<result.length; i++) {
$("#targetDrop").append("<option name=\"targetDB\" value=\"" + result[i] + "\">" + result[i] + "</option>");
}
})
.fail(errorFn)
.always(function (data,textStatus,jqXHR){
console.log("The request is complete!")
});
My problem, is that you have to click the dropdown once (nothing shows), deselect it, and then click it again to see the populated values. It makes sense, seeing as its taking the click to generate the data, so I need to reselect the dropdown to see the new data.
Is there a way of making this all happen on the first click?
Thanks!
There is another more effective way of achieving this:
$("#targetHost, #targetPort").change(function () {
if ($.trim($("#targetHost:checked").val()) != "" && $.trim($("#targetPort:checked").val()) != "") {
dbLookUp();
}
});
function dbLookUp() {
var data = {
host: $("#targetHost:checked").val(),
port: $("#targetPort:checked").val()
}
$.ajax({
url: './dbLookup.php',
type: 'POST',
dataType: "json",
data: data,
}).done(function(response) {
var opts = '<option value="">Choose Database...</option>';
$.each(response, function(index, data) {
opts += '<option name="targetDB" value="' + data + '">' + data + '</option>';
});
$("#targetDrop").html(opts);
}).fail(function(response) {
console.log(response);
});
}
dbLookUp(); // Add this line if you have default selection for host and port
// and you want to load the DB list as soon as the page loads up.
In this way you don't have to click on the dropdown to get it loaded... As soon as you select the host and port it will load up the doropdown. You can even load the db list on first page load.
Hope this helps.

populate dropdown via ajax and automatically select a value

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

Categories

Resources