I have three relational dropdown like if i select the program dropdown then it should populate the years and when i select the year it should populate blocks , i wrote the javascript for it it is working fine but there is an issue like on page load the events are not fired i need to select the dropdown list value and then change it to fire the event secondly on third dropdown its value did not get refreshed when i changed the dropdown of first dropdown list can someone suggest me how to fix these two issues
below is my code
$("#ddlProgram").change(function () {
$("#ddlYear").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getCity")',
dataType: 'json',
data: { id: $("#ddlProgram").val() },
success: function (states) {
$.each(states, function (i, state) {
$("#ddlYear").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve Year information.' + ex);
}
});
return false;
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#ddlYear").change(function () {
$("#ddlBlock").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getBlocks")',
dataType: 'json',
data: {
id: $("#ddlYear").val(),
programid: $("#ddlProgram").val()
},
success: function (states) {
$.each(states, function (i, state) {
$("#ddlBlock").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve information.' + ex);
}
});
return false;
})
});
</script>```
Related
I'm using a select2 to allow the user to select multiple options. Everything is working fine, except for one frustrating issue.
The first time I click the save button to save the items, it works. But then on subsequent calls, the ID of the items are replaced with the position of the items. For for example, if I have IDs 3, 6 and 10 selected, the first Save will work and 3,6,10 are passed to the controller.
But then if I reload the view and click save, the numbers 0,1,2 are passed in (ie, their relative positions in the select).
Here is the code:
Firstly, the HTML:
<select id="selectGroup" class="form-control" multiple="true">
On $(document).ready:
// Load Groups
$("#selectGroup").select2({ placeholder: 'Select' });
$.ajax({
url: ROOT_URL + "Group/GroupList",
type: "GET",
success: function (data) {
let dropdown = $('#selectGroup');
dropdown.empty();
dropdown.append($('<option></option>').attr('value', 0).text("(Select)"));
$.each(JSON.parse(data), function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.GroupID).text(entry.GroupName));
})
},
error: function (passParams) {
Notify(passParams, "Unexpected Error Loading Groups", "error");
}
});
And finally the js for the save (called from a button which passes in the loanID):
function LoanGroupSave(loanID) {
var grpIDs = '';
[].forEach.call(document.querySelectorAll('#selectGroup :checked'), function (elm) {
grpIDs += elm.value + ',';
})
var editURL = location.protocol + '//' + location.host + "/Loan/LoanGroupSave";
//alert(editURL);
var obj = { "LoanID": loanID, "GroupIDs": grpIDs };
alert(JSON.stringify(obj));
$.ajax({
type: "POST",
url: editURL,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (response) {
if (response.success) {
Notify("Group(s) information has been saved", "Saved", "success", false, "toast-top-right", 5000);
}
else {
OpenPopupGeneral("Error(s)", response.message);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
OpenPopupGeneral("Unexpected Error(s)", "Error = " + errorThrown);
});
}
Posting for people who make the same mistake.
Problem was in my load - I needed to add the GroupID as the key, not the row number which was in the key parameter value:
success: function (data) {
$.each(JSON.parse(data), function (key, entry) {
var $newOption = $("<option selected='selected'></option>").val(entry.GroupID).text(entry.GroupName);
$("#selectGroup").append($newOption).trigger('change');
}
Hi StackOverflow and fellow developers...
So. I really enjoy Materialize CSS, but it can get to my head sometimes.
I have some select elements on my site, which is very nice, and the initialization works fine and they are displayed.
I then have another function to populate the selects, and according to the Materialize documentation i should just run $('select').material_select();again. Unfortunately when i try to call the function for the second time i get the error Uncaught TypeError: $(...).material_select is not a function.
I can't understand why i can't call the function when i just did in the document ready function?
JS Bundle For Page:
Blockquote
$(document).ready(function () {
// This works fine and as expected my Selects are rendered perfect
$('select').material_select();
fetchSoftware();
getusersinit();
});
var fetchSoftware = function fetchSoftware() {
$.ajax({
type: "Get",
url: "Dashboard/GetSoftwares",
data: { userName: "*****" },
success: function success(softwares) {
console.log(softwares);
$("#softwareSelectDefault").remove();
Object.keys(softwares).forEach(function (key) {
$("#softwareSelect").append("<option>" + softwares[key] + "</option>");
});
//Down here shit falls apart. This doesen't work
$('select').material_select();
},
error: function error(errorMessage) {
//window.location.href = "/account/signin";
}
});
};
var getusersinit = function getusersinit() {
$.ajax({
type: "Get",
url: "***********",
data: { userName: "**********" },
success: function success(reports) {
console.log(reports);
$(".progress").remove();
Object.keys(reports).forEach(function (key) {
$("#******").append("<tr id=\"" + reports[key].id + "\"><td><i class=\"medium material-icons\">" + reports[key].locked + "</i></td><td><i class=\"medium material-icons\">" + reports[key].status + "</i></td><td>" + reports[key].user + "</td><td>" + reports[key].script + "</td><td>" + reports[key].software + "</td><td>" + reports[key].testBench + "</td><td>" + reports[key].repository + "</td><td>" + reports[key].executionTime + "</td><td>" + reports[key].startDate + "</td></tr>");
});
},
error: function error(errorMessage) {
window.location.href = "/account/signin";
}
});
};
Update 10-04-2018
So, after spending almost the whole workday yesterday on this problem, I'm now a little closer to a solution.
I discovered something very strange. Apparently, the problem lies in my ajax call. I have a theory, that it depends on the url or reply.
$(document).ready(function () {
//fetchSoftware works. If i run getuserinit it does not. Then material_select doesen't exist
fetchSoftware();
});
var fetchSoftware = function fetchSoftware() {
$.ajax({
type: "Get",
url: "https://jsonplaceholder.typicode.com/posts/1",
data: { userName: "XXXXXX" },
success: function (result) {
$("#testReports").append(`<tr><td>TEST</td></tr>`);
$("#softwareSelect").append(`<option>Test Option</option>`);
$('#softwareSelect').material_select();
},
error: (errorMessage) => {
window.location.href = "/account/signin";
}
});
};
var getusersinit = function getuserinit() {
$.ajax({
type: "Get",
url: "Dashboard/LoadTable",
data: { userName: "XXXXXX" },
success: function (result) {
$("#testReports").append(`<tr><td>TEST</td></tr>`);
$("#softwareSelect").append(`<option>Test Option</option>`);
$('#softwareSelect').material_select();
},
error: (errorMessage) => {
window.location.href = "/account/signin";
}
});
};
formSelect() is the new method.
Use selectSoftware.formSelect(); instead of material_select()
I fixed the issue, though it is a workaround.
Put the selects in variables...
/*
These constant are created because of an unsolved issue:
See https://stackoverflow.com/questions/49728000/
By putting the selects into constants, and only referencing the constants,
this is a workaround.
*/
var selectSoftware = $('#softwareSelect');
$(document).ready(function () {
selectSoftware.material_select();
getSoftware();
});
var getSoftware = function getSoftware() {
$.ajax({
type: "Get",
url: "Dashboard/GetSoftwares",
data: { userName: "XXXXXXX" },
success: function success(softwares) {
console.log(softwares);
$("#softwareSelectDefault").remove();
Object.keys(softwares).forEach(function (key) {
$("#softwareSelect").append("<option>" + softwares[key] + "</option>");
});
selectSoftware.material_select();
},
error: function error(errorMessage) {
//window.location.href = "/account/signin";
}
});
};
I'm using asp.net webservice to use it in jQuery UI autocomplete plugin and here is the data I'm getting.
{"d":[
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":3,
"SubCommodityName":"Urid Dal",
"BrandId":3,
"BrandName":"President"
},
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":1,
"SubCommodityName":"Red Gram",
"BrandId":4,
"BrandName":"President"
}
]
}
This is the script I'm using:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.BrandName,
label: item.SubCommodityName
}
}))
},
error: function (response) {
alert('error');
},
failure: function (response) {
alert('faii');
}
});
},
select: function (e, i) {
console.log(i.MainCommodityId);
console.log(i.SubcommodityId);
console.log(i.BrandId);
},
minLength: 1
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + "" + item.BrandName + " in " + item.MainCommodityName + " - " + item.SubCommodityName + "</a>")
.appendTo(ul);
};
});
The issues are:
When I tried to enter keyword say: pre the aforesaid output is coming in json. However, the list is returning only one "President" item where it should display 2 items.
The list is displaying "undefined in undefined - undefined" instead of values after adding .autocomplete("instance")._renderItem function.
console.logs are also undefined after selecting an item.
How can these issues fixed?
The default behavior of the select event is to update the input with ui.item.value. This code runs after your event handler.
Simply prevent the default action on select and focus using event.preventDefault() or by return false and use _renderItem for custom dropdown.
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault(); // or return false;
}
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
//do something
}
References:
jQuery UI Autocomplete Examples
Example 2
Finally, I was able to achieve what I wanted. Answering my question as it may helpful to someone.
javascript:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
// don't forget to $.map to (data.d where d is the top node
return {
// assign values from json response for further use
brandid: item.BrandId,
brand: item.BrandName,
maincommodityid: item.MainCommodityId,
maincommodity: item.MainCommodityName,
subcommodityid: item.SubcommodityId,
subcommodity: item.SubCommodityName
}
}));
},
error: function (response) {
alert('Server Error. Please try again.');
},
failure: function (response) {
alert('Failed to get result');
}
});
},
focus: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
},
select: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// do further action here such as assigning id to hidden field etc.
$(".input-search").val(ui.item.brand);
// navigate to the selected item's url ex: /catalogue/1/1/pulses/red-gram/4/president
var str = "/catalogue/" + ui.item.maincommodityid + "/" +
ui.item.subcommodityid + "/" + $.trim(ui.item.maincommodity.replace(/\s+/g, '-').toLowerCase()) + "/" +
$.trim(ui.item.subcommodity.replace(/\s+/g, '-').toLowerCase()) + "/" + ui.item.brandid + "/" +
$.trim(ui.item.brand.replace(/\s+/g, '-').toLowerCase());
window.location = str;
},
minLength: 3
}).autocomplete("instance")._renderItem = function (ul, item) {
// get values and create custom display
var $a = $("<a></a>");
$("<strong></strong>").text(item.brand).appendTo($a);
$("<span></span>").text(" in ").appendTo($a);
$("<span></span>").text(item.subcommodity).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};
});
CSS:
ul.ui-front {
z-index: 1200; // change z-index according to your UI.
}
Usually I do this way and Its work.
$(document).ready(function () {
var jsondata=array();
$.post("/WebServices/GetAllBrandNames.asmx/getAllBrands",{data: request.term},function(data){
var data=JSON.parse(data);
$.each(data.d, function( index, value ) {
jsondata[index].value=value;
});
$(".input-search").autocomplete({
source:jsondata,
//other property and events
})
});
I mean apply source JSON after completing request because sometimes if AJAX takes some time to load execution pointer still execute rest of code without waiting for response.
I did not test this code but I always do this way and never get your kind of error. Good Luck
I am developing textbox with autocomplete using jQuery UI Autocomplete.
After that, I can create textbox with autocomplete, but one issuce has occured now.
In my textbox, I want to prevent selecting specific item from autocomplete list.
If I select specific item, Autocomplete list display again or not to close.
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
});
});
});
If someone know answer, please teach me.
Based on the example from here: How to disable element in jQuery autocomplete list
I think this code will work for you:
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
var id = item.id
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
If you can provide a working version of your code (the items can also be from a predefined list, not based on ajax call) it will be much easier to help.
Using Jquery autocomplete UI widget, I have the following code that gets a list of suburbs/postcodes via external php:
<script>
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
}
});
});
</script>
The autocomplete itself works well, I get the list of matches , however the 'select' part does not work, ie, I need to set another input text value to the value selected, but even in the above code, the Alert dialog does not get called - the various syntax I've seen has kind of confused me, so I'm not sure what I've done wrong here.
The selectfunction should be outside of the object that is sent to the ajax method.
Try this:
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
}
});
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
});