Checkbox not refreshing in jquery - javascript

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

Related

Close Select2 Dropdown after clicking on X to Clear

I'm trying to get a Select2 Dropdown to close after clicking on X to clear it because it stays open. I'm currently using the .on('select2:unselect') function to trigger it when the button is clicked to clear the selections but I either get an error or it just doesn't do anything.
Error
TypeError: Cannot read properties of null (reading 'query')
Select2 HTML
<select class="softwareReleaseItem" name="softwareReleaseItem" id="softwareReleaseItem" data-control="select2">
<option></option>
<?php
asort($softwaredb);
foreach ($softwareDB as $software) {
echo "<option value=\"" . $software['Guid'] . "\">" . strtoupper($software['Name']) . "</option>";
}
?>
</select>
<div id="sRI"></div>
Javascript
$('.softwareReleaseItem').on('select2:select', function(e) {
var sri_data = e.params.data;
var sri_callType = 'softwareReleaseItem';
//console.log(sri_data);
$("#sRI").show();
$.ajax({
type: "POST",
url: "dist/php/ajax/ajax_getItemsByName.php",
data: {
sri_id: sri_data['id'],
sri_text: sri_data['text'],
sri_call: sri_callType
},
success: function(data) {
$('#sRI').html(data);
}
});
}).on('select2:unselect', function(e) {
$("#sRI").hide();
closeSelect();
});
All my attempts to close it ->
function closeSelect() {
//$('.softwareReleaseItem').trigger('select2:close');
//$(".softwareReleaseItem").focusout();
$(".softwareReleaseItem").select2().trigger('close');
//$("#softwareReleaseItem").select2("select2:close");
//$("#select2-drop-mask").click();
//$(document.body).trigger('mousedown');
//$('body').trigger('mousedown');
//$('.select2-hidden-accessible').select2('select2:close');
//$(".softwareReleaseItem").select2("select2:close");
};
UPDATE:
So far this is the only working solution I have come up with that works
I just simulate a mouseclick on a hidden div.
.on('select2:unselect', function(e) {
$("#sRI").hide();
$(".softwareReleaseItem").trigger("reset").trigger("change")
document.getElementById('#sRI')
.dispatchEvent(new MouseEvent('click', {
shiftKey: true
}))
});

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) {
}
});};

Bootstrap multiselect dropdown .val() not updating

I have 3 drop downs which are cascading.
Zone -- > Region --> Territory
I am using Bootstrap multiselect drop downs.
When i select the Zone drop down the respective regions are to be bound
and simultaneously the newly bound regions' territories are to be bound to the territory drop down.
Here is my drop-down initialisation code.
$('#ddlZone').multiselect({
enableClickableOptGroups: true,
enableCollapsibleOptGroups: true,
enableFiltering: true,
includeSelectAllOption: true,
nonSelectedText: 'Select Zone',
enableCaseInsensitiveFiltering: true,
selectAllNumber: true,
onChange: function(option, checked,select) {
FillRegionsDropdown();
FillTerritoriesDropdown();
}
Here is the code for the above functions.
function FillRegionsDropdown()
{
var Zone=$('#ddlZone').val();
if(Zone != null)
{
Zone= Zone.join(",");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("BindRegionsOnZonesAjax", "GeoMap")",
data: "{ZoneIds:'" + Zone + "'}",
success: function (Result)
{
$("#ddlRegion").html("");
$('#ddlRegion').multiselect( 'refresh' );
$.each(Result, function (key, value) {
$("#ddlRegion").append($("<option></option>").val(value.Value).html(value.Text));
});
$('#ddlRegion').multiselect( 'rebuild' );
$("#ddlRegion").multiselect('selectAll', false);
$("#ddlRegion").multiselect('updateButtonText');
}
});
}
}
The above code works perfectly i.e. on Zone dropdowns change the regions get bound and set to select all.
But the issue is with Binding territory drop down with zone drop down change.
And here is the code for Territory dropdowns binding.
function FillTerritoriesDropdown()
{
var rgns=$('#ddlRegion').val();
if(rgns != null)
{
rgns= rgns.join(",");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("BindTerritoriesOnRegionsAjax", "GeoMap")",
data: "{RegionIds:'" + rgns + "'}",
success: function (Result)
{
$("#ddlTerritory").html("");
$('#ddlTerritory').multiselect( 'refresh' );
$.each(Result, function (key, value) {
$("#ddlTerritory").append($("<option></option>").val(value.Value).html(value.Text));
});
$('#ddlTerritory').multiselect( 'rebuild' );
$("#ddlTerritory").multiselect('selectAll', false);
$("#ddlTerritory").multiselect('updateButtonText');
}
});
}
}
Here the $('#ddlRegion').val() doesn't get updated to the newly bound region values which is caused due to zone drop down change.
$('#ddlRegion').val() still contains the initial page load region values.
I have been struck with this for more than 6 hours now.
Can some one help me to fix this issue?,
Try using async:false in both FillTerritoriesDropdown() and FillREgionsDropdown() functions. i.e. in the ajaxcalls to the controller of those 2 functions.

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