I need to create a dropdownlist with the Region (Asia, South East Asia, North America,..etc) and the Country together in the same dropdownlist.
Upon selecting the options, then i will populate the City based on the Country selected.
It will look something like this, but in a dropdownlist instead of expanding it out.
With Singapore, Australia, Cambodia,etc as Region in my case, and the Cities shown, as Country.
Or more specifically, like the following , with Taiwan, Mainland China as Region, and the Cities as Country for my case.:
All my data are pulled from my database, with my RegionTable that looks like this
and my CountryTable like this :
I've got the code working fine for populating the cities based on Country selected, the problem now is that i do not know how to put the region into the same dropdown with the Country. The only problem is how do i add in the Region and making it not selectable because, users should be selecting the Country instead of the Region.
Im using the following code to get my CountryDropDownList
function loadPackage_CountryList() {
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', true);
$("#Package_Country").append("<option value=''>Downloading...</option>");
$.ajax({
type: "POST", url: PackageWSURL + "/GetPackageCountryList", data: "",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
var countries = response.d;
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', false);
for (var i = 0; i < countries.length; i++) {
$("#Package_Country").append("<option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>");
}
}
});
}
Anybody can help me on how to add Region into the Dropdownlist?
Thanks in advance.
--------------Edited----------------------
This is my WebMethod of getting the data from my database.
[WebMethod]
public List<jsonItem> GetPackageCountryList()
{
List<jsonItem> RecordList = new List<jsonItem>();
jsonItem jItemA = new jsonItem();
jItemA.Display = "All Countries";
jItemA.Value = "ALL";
jItemA.Group = "---";
RecordList.Add(jItemA);
String ConnStr = WebConfigurationManager.ConnectionStrings["TOUR_DB_ConStr"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnStr);
connection.Open();
try
{
String SQL = "SELECT [CountryList].[CountryCode], [CountryList].[CountryName], [CountryList].[Regioncode] ";
SQL += "FROM [CountryTable] ";
SQL += "WHERE [CountryTable].[Activation] = 1 ";
SQL += "ORDER BY [CountryTable].[Regioncode], [CountryTable].[CountryName]";
SqlCommand command = new SqlCommand(SQL, connection);
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
jsonItem RecordItem = new jsonItem();
RecordItem.Display = dataReader["CountryName"].ToString() + " - " + dataReader["CountryCode"].ToString();
RecordItem.Value = dataReader["CountryCode"].ToString();
RecordItem.Group = getRegionName(dataReader["RegionCode"].ToString());
RecordList.Add(RecordItem);
}
dataReader.Close();
}
catch { }
finally
{
connection.Close();
}
return RecordList;
}
I've managed to add in the optgroup from the function below, but the problem now is that i think it will auto add in the <optgroup> at the end of the line even though i've add in the if else function.
function loadPackage_CountryList() {
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', true);
$("#Package_Country").append("<option value=''>Downloading...</option>");
$.ajax({
type: "POST", url: PackageWSURL + "/GetPackageCountryList", data: "",
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
var countries = response.d;
var group = "";
$('#Package_Country option').each(function (i, option) { $(option).remove(); });
$('#Package_Country').attr('disabled', false);
for (var i = 0; i < countries.length; i++) {
group = countries[i].Group;
if (group != "---") {
$("#Package_Country").append("<optgroup label='" + countries[i].Group + "'><option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>");
if (group != countries[i].Group)
{ $("#Package_Country").append("</optgroup>"); }
else { continue; }
}
else { $("#Package_Country").append("<option value='" + countries[i].Value + "'>" + countries[i].Display + "</option>"); }
}
}
});
}
so now it looks like this instead
notice how Asia got repeated.
I think you should use optgroup feature of select. If you can point the tech you use (WebForms, MVC) I can further help
Edit
I would change your for with this code
var selectCountries = $("select#Package_Country");
for (var i = 0; i < countries.length; i++) {
group = countries[i].Group;
var optgroupRegion = null;
if (group !== "---") {
optgroupRegion = selectCountries.find("optgroup[label='" + group + "']");
if (optgroupRegion.length === 0) {
optgroupRegion = $("<optgroup></optgroup>").attr("label", group).appendTo(selectCountries);
}
}
$("<option></option>").val(countries[i].Value).text(countries[i].Display).appendTo(optgroupRegion !== null ? optgroupRegion : selectCountries);
}
The updated code would reuse an already added optgroup.
Related
I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.
Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.
i need to recover the id of element selected in combobox in dev express
and this is the code of combobox:
#Html.DevExpress().ComboBox(
settings =>
{
settings.Name = "comboBox4";
settings.Width = 180;
settings.SelectedIndex = 0;
settings.Properties.DropDownWidth = 550;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Editors", Action = "MultiColumnComboBoxPartial" };
settings.Properties.CallbackPageSize = 30;
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
settings.Properties.TextFormatString = "{1}";
settings.Properties.ValueField = "Id";
settings.Properties.ValueType = typeof(string);
settings.Properties.Columns.Add("Id", "Id", 130).SetColVisible(false);
// settings.Properties.Columns.Add("Id", "Id", 130).SetColVisibleIndex(1);
settings.Properties.Columns.Add("Nom", "Nom", 130);
settings.Properties.Columns.Add("Prenom", "Prenom", Unit.Percentage(100));
settings.Properties.Columns.Add("DateNaissance", "DateNaissance", 60);
settings.Properties.Columns.Add("CodeClient", "CodeClient", 100);
}
).BindList(client).GetHtml()
and this the method ajax how i put the value of any custom with ajax:
function Addprojet() {
debugger;
var nom = $("#nom2_I").val();
var description = $("#Description_I").val();
var client = $("#comboBox4_I").val();
var chef = $("#chefid_I").val();
var complexite = $("#comboBox1_I").val();
var taille = $("#comboBox2_I").val();
var datedebut = $("#datedebut_I").val();
$.ajax({
url: "/Projet/AjouterProjet?nom=" + nom + "&description=" + description + "&client=" + client + "&chef=" + chef + "&complexite=" + complexite + "&taille=" + taille + "&datedebut=" + datedebut, // /Controlleur/Action
type: "POST",
dataType: 'text',
//data : {Nom: nom},
success: function (responseText) {
debugger;
if (responseText == "True") {
location.replace("/Client/listeclients");
}
else {
alert("error");
}
}
});
}
</script>
how can i resolve this issue because i need to recover the id of client without displaying in the list in the combobox
can semeone help me to fix it .
I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},
I wanted to get Json data from web method.In here i wanted to get News & Speaker both data but here only working News only.(Unable to get Speaker )
Here is my Stored Procedure
ALTER procedure [dbo].[LoadDayEvents]
#Date date
as
begin
select News,Speaker from Eventstbl
where DateToBePublished = CONVERT(date, #Date)
end
Here is my Web Method
[WebMethod, ScriptMethod]
public static string SelectEventDate(string date)
{
string News= "";
string Speaker = "";
try
{
SqlCommand comld = new SqlCommand("LoadDayEvents", conDB);
comld.CommandType = CommandType.StoredProcedure;
comld .Parameters.Add("#Date", SqlDbType.Date);
comld .Parameters["#Date"].Value = DateTime.Parse(date).Date;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
News = comld .ExecuteScalar().ToString();
Speaker = comld .ExecuteScalar().ToString(); // Thisone is not working
}
catch (Exception ee) { }
finally { conDB.Close(); }
return News;
}
Here i use Ajax/Json to get it
<script type="text/javascript">
$(document).ready(function () {
var urinews = '<%= ResolveUrl("WebMethods.aspx/SelectEventDate") %>';
var localtime = new Date();
var today = localtime.getFullYear() + '/' + (localtime.getMonth() + 1) + '/' + localtime.getDate();
$.ajax({
type: "POST",
url: urinews,
data: "{ date: '" + today + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#daily_news_Selection").append("<p>" + msg.d + "</p>");
},
error: function (x, e) {
}
});
});
</script>
You could return custom class
var newsAndSpeaker = new NewsAndApeaker() { News = News, Speaker = Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables using
msg.d.News //news
msg.d.Speaker
Or, you could return a list of string
var newsAndSpeaker = new List<string>() { News, Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables as in like a array
msg.d[0] //mews
msg.d.[1] //speaker
If your question is why your second property is not getting populated, then title seems to be wrong
Nothing happaned when i try do this in release mode but in debug mode all work fine - why???
When i adding button and outputing data by clicking this buton.My inner links in my list rows work fine also ( http://clip2net.com/s/2AG04 ).And only on $(document).ready(function () { event this doesn't want to work...
On client i have:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Index", "Product")',
cache: false,
type: 'GET',
dataType: 'json',
proccessData: false,
contentType: 'application/json; charset=utf-8'
});
On server i have this:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
//Отправляем на клиент данные
_senderHub.SendMessage();
return null;
}
return View();
}
Also on server:(SignalR)
readonly ManagerDB _managerDB = new ManagerDB();
public void SendMessage()
{
IEnumerable<ProductModels> list = _managerDB.GetListOfProduct1();
var listToClient = new List<ProductModels>();
foreach (var prod in list)
{
listToClient.Add(new ProductModels
{
Id = prod.Id,
Name = prod.Name,
LockType = prod.LockType,
LockTime = prod.LockTime,
LockUser = prod.LockUser,
TimeStampF = prod.TimeStampF
});
}
var anonimProduct = listToClient;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SenderHub>();
context.Clients.AddListRows(anonimProduct);
}
On client(SignalR) trying catch this data:
$(function () {
var senderHub = $.connection.senderHub;
senderHub.AddListRows = function (data) {
var dataFromServer = data;
var listOfData = "";
for (var i = 0; i < dataFromServer.length; i++) {
$("#ListOfProductsTableBody").html(null);
var userId = '';
if (dataFromServer[i].LockUser != null) {
userId = dataFromServer[i].LockUser;
}
listOfData += ("<tr><td>" + dataFromServer[i].Id + "</td><td>" + dataFromServer[i].Name + "</td><td>" + userId + "</td><td>" + dataFromServer[i].LockType + "</td>" + "<td id=\"ModifyBlock\"><a id=\"Detail\" href=\"#\" alt=" + dataFromServer[i].Id + " >Детально</a>|<a id=\"Delete\" href=\"#\" alt=" + dataFromServer[i].Id + " >Удалить</a>|<a id=\"Edit\" href=\"#\" class=\"" + dataFromServer[i].LockTime + "\" alt=" + dataFromServer[i].Id + " >Редактировать</a></td></td></tr>");
}
$("#ListOfProductsTableBody").append(listOfData);
};
$.connection.hub.start();
});
emphasized text
See David Fowler's response to my question. Looks like you have the same issue.
Server to client messages not going through with SignalR in ASP.NET MVC 4