How to clear the text of a linked dropdown (selectpicker) using javascript? - 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) {
}
});};

Related

Input value updated with .val() not display until field clicked

I have a drop down that when a value is selected, there is an ajax query that updates the last input field (Taux de...).
$.ajax({
type: "GET",
cache: false,
url: '/Product/AgentCommissionBaseRate/' + $('input[name=ProductOid]').val() + "_" + $('input[name=Insurer]').val(),
success: function(data) {
//attempt1
document.getElementById('AgentCommissionBaseRate').setAttribute('value', data);
//attempt2
$('#AgentCommissionBaseRate').attr("value", data);
//attempt3
$('#AgentCommissionBaseRate').val(data);
alert($('#AgentCommissionBaseRate').val()) < --Shows proper value
}
});
If I check with an alert box, the value is properly updated. But the new value doesn't show in the input UNTIL I CLICK ON THE FIELD. Been stuggleing for a while on this!

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

Populating JSON array to drop down reserved word column name conflict

This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example

Adding additional options to select using ajax

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

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.

Categories

Resources