I have 2 drop down list (ul dropdown) , need to populate 2nd based on first one selection.
here is the full code
<div id="dd" class="wrapper-dropdown-1 brderRad" tabindex="1">
<span>From Any Country</span>
<ul class="dropdown">
#foreach (var country in Model.country_list)
{
<li class="coun" id="#country.country_id">#country.country_name</li>
}
</ul>
</div>
<div id="dd2" class="wrapper-dropdown-1 brderRad" tabindex="1">
<span>From Any City</span>
<ul class="dropdown city_drop" id="city_drop_id">
</ul>
</div>
JS
<script type="text/javascript">
$(document).ready(function () {
$('.coun').click(function () {
var id = ($(this).attr('id'));
$("#city_drop_id").empty();
$.ajax({
url: '#Url.Action("GetCityList", "Home")',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ id: $(this).attr('id') }),
success: function (data) {
if (data.success) {
var dataa = data.dataDic;
$.each(dataa, function (i, item) {
$('#city_drop_id').append('<li class="selected" value="' + item.ID + '">' + item.Name + '</li>');
});
// $('#city_drop_id').dropdown('refresh');
} else {
alert('Failed');
}
}
});
});
});
</script>
Controller - to retrieve city list based on country selection
[HttpPost]
public JsonResult GetCityList(string id)
{
Dictionary<int, string> cityDic = new Dictionary<int, string>();
cityDic = citydbRep.GetAllCityList().Where(i=>i.city_country_id
==Convert.ToInt32(id)).ToDictionary(t => t.city_id, t => t.city_name);
var dataDic = cityDic.Select(u => new
{
ID = u.Key,
Name = u.Value
});
return Json(new { success = true, dataDic });
}
Now append is working fine, but couldn't able to select the value from 2nd drop down (city ) .
please any one suggest the way to solve this?
Thank you
you need to add cascade drop down. you can achieve this on change function
[yourID].onchange = function () {
}
look this for more detail
Related
I'm working on creating two dropdown lists for a form. The first is a list of Areas and the second needs to filter to the Job Types based on the selected Area.
I'm basing the majority of my code on this answer, but am having trouble getting the Job Types list to show in the View. I can see the correct options being appended when debugging, but am stuck on why they are not populating the Job Type dropdown list.
The View
<!--Area Dropdown-->
#Html.DropDownList("areas", null , new { #class = "col s12 m6 l3" })
<!--Job Type Dropdown-->
#Html.DropDownList("jobType", Enumerable.Empty<SelectListItem>(), "Job Type", new { #class = "col s12 m6 l3" })
The controller code, which is populating my first dropdown box (Area)
var jobArea = (from a in db.tblJobTypes
where a.Active == true
select a.Department).Distinct().ToList();
ViewData["areas"] = new SelectList(jobArea);
The POST action within the controller
[HttpPost]
public ActionResult JobTypeByArea(string area)
{
var test = (from a in db.tblJobTypes
where a.Active == true && a.Department == area
select new
{
id = a.JobTypeID,
job = a.JobType
}).ToList();
return Json(test, JsonRequestBehavior.AllowGet);
}
And finally, the JQuery
$(document).ready(function () {
$('#areas').change(function () {
$.ajax({
url: '/Home/JobTypeByArea',
type: 'POST',
data: { area: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
var category = $('#jobType');
$.each(data, function () {
options += '<option value="' + this.id + '">' + this.job + '</option>';
});
$('#jobType').append(options);
},
});
});
});
Chosen plug-in is not working when i create the element dynamically
i created Select list dynamically from ajax response and the problem is Chosen plug-in not working with it , Please help me to solve it
here is my code:
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },
success: function (data) {
if (data.length > 0) {
console.log(data)
$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});
$("#Div1").empty();
$("#Div1").append($SubListSelect);
}
else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
and and plugin code:
$(document).ready(function ($) {
$(function () {
$("#SubListSelect").chosen();
});
Thank you
My proposal:
in my demo I used a different url for the ajax and I figured out a possible HTML.
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>
I assume the select is in #Div1 which you are emptying, then re-appending.
in that case you need to re-initialize it:-
$("#Div1").empty();
$("#Div1").append($SubListSelect);
$("#SubListSelect").chosen();
A better option though would be to only empty the select and re-append the options to the select without emptying the #Div1. then call:-
$("#SubListSelect").trigger("chosen:updated");
also, this
$(document).ready(function ($) {
and this
$(function () {
mean the same thing, with the latter being short hand. Therefore you only need one.
I am working on an asp.net application where i have to an ul tag. Here is my design view
<ul class="products_list" id="ulProductCart">
<li>
<div class="clearfix">
<img class="f_left m_right_10" src="" alt="">
<div class="f_left product_description">
<span class="f_size_medium"></span>
</div>
<div class="f_left f_size_medium">
<div class="clearfix">
1 x <b class="color_dark">$99.00</b>
</div>
<button class="close_product color_dark tr_hover"><i class="fa fa-times"></i></button>
</div>
</div>
</li>
</ul>
i am using jquery to bind this ul tag. Following is my jquery code to bind to the ul tag
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
id = 1;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Default.aspx/BindCart",
data: "{'UID':'" + id + "'}",
dataType: "json",
async: true,
success: OnImageSuccess,
error: OnImageError,
failure: function (response) {
alert('Fail');
}
});
function OnImageSuccess(response) {
var ulProductCart = document.getElementById("ulProductCart");
$.each(response.d, function (key, value) {
ulProductCart.append("<li><div><img src=" + value.ImgProduct + " style=width:50px height:50px /><div><a>" + value.ProductName + "</a><span>" + value.ProductCode + "</div><div><div>1*<b>" + value.Price + "</b></div><button><i></i></button></div> </div></li>");
})
alert('succeed');
}
function OnImageError(response) {
alert(response.d);
}
});
</script>
My Web Method is:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod(enableSession: true)]
public static Products[] BindCart(string UID)
{
DataTable dt = new DataTable();
List<Products> details = new List<Products>();
//HtmlAnchor a = new HtmlAnchor();
//a.InnerHtml
dt = new ProductImages().SelectProductsWithImagesByProductID(Convert.ToInt64(UID));
foreach (DataRow dtrow in dt.Rows)
{
Products Products = new Products();
Products.ProductCode = dtrow["ProductCode"].ToString();
Products.ProductName = dtrow["ProductName"].ToString();
Products.ImgProduct = dtrow["ImgProduct"].ToString();
Products.Price = Convert.ToDecimal(dtrow["Price"].ToString());
details.Add(Products);
}
return details.ToArray();
}
My above code fetches the appropriate data from database but when it goes to bind the ul tag it dows not gets bind.Also it goes to OnImageSuccess Mrthod used in jquery but my ul tag is not getting bind.
Issue in the below line
var ulProductCart = document.getElementById("ulProductCart"); // not a jQuery object
append is a jQuery function , so u need to use jquery selector.
use this :
var ulProductCart = $("#ulProductCart");
Sample :
function OnImageSuccess(response) {
// var ulProductCart = document.getElementById("ulProductCart");
var ulProductCart = $("#ulProductCart");
$.each(response.d, function (key, value) {
ulProductCart.append("<li><div><img src=" + value.ImgProduct + " style=width:50px height:50px /><div><a>" + value.ProductName + "</a><span>" + value.ProductCode + "</div><div><div>1*<b>" + value.Price + "</b></div><button><i></i></button></div> </div></li>");
})
alert('succeed');
}
I'm busy with 2 drop downs. The first one is country and loads fine, then on country change I call ajax to populate the province drop down.
The code works fine and when I put an alert in my ajax call it shows the correct data being created but it doesn't append it the drop down so the values aren't available.
Drop Down
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Country:</label>
<div class="col-md-9 col-xs-7">
#Html.DropDownListFor(x => x.CountryId, (IEnumerable<SelectListItem>)ViewBag.CountryItems, "Please Select", new { #id = "ddlCountry", #class = "form-control select" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Province:</label>
<div class="col-md-9 col-xs-7">
#Html.DropDownListFor(x => x.ProvinceId, Enumerable.Empty<SelectListItem>(), "Please Select", new { #id = "ddlProvince", #class = "form-control select" })
</div>
</div>
The Ajax
<script>
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;
$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
$.each(data, function (i) {
var optionhtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionhtml);
});
}
});
});
</script>
The code behind
public ActionResult GetProvinces(string countryId)
{
IEnumerable<SelectListItem> ProvinceItems = null;
if (!string.IsNullOrEmpty(countryId))
{
ProvinceItems = BusinessAPI.ProvinceManager.GetAllProvincesByCountryId(Convert.ToInt32(countryId)).Select(ci => new SelectListItem
{
Value = ci.Id.ToString(),
Text = ci.Name
});
}
return Json(ProvinceItems, JsonRequestBehavior.AllowGet);
}
I found the problem.
I have a javascript file in there thats causing some issues.
<script type="text/javascript" src="../../Scripts/js/plugins/bootstrap/bootstrap-select.js"></script>
This came with the template I bought and it helps with the way the dropdowns and stuff works.
With that javascript file you have to add .selectpicker('refresh'); to the append to load it properly like this
$("#ddlProvince").append(optionshtml).selectpicker('refresh');
That might be slow when loading a large amount of data so just refreshing the dropdown once after everything done works well. Here is the code that works well for me now
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;
$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
async: true,
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
("#ddlProvince").empty();
$.each(data, function (i) {
var optionshtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionshtml);
});
$("#ddlProvince").selectpicker('refresh');
}
});
});
I have been trying to cascade dropdown lists. For this purpose I am using javascript in .cshtml page . Don't know what is the reason , I'm not able to even call Js method , leave alone the controller method which later needs to be called from within the Js method. Dropdowns are fetching the state and city data but I'm not getting the city according to the state selected.
<div class="editor-label">
#Html.LabelFor(model => model.State_Id)
</div>
<div class="editor-field">
#Html.DropDownList("State",null,"Select State", new {#class="span4", id="State"})
#Html.ValidationMessageFor(model => model.State_Id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CityId)
</div>
<div class="editor-field">
#Html.DropDownList("City",null,"Select City", new {#class="span4", id="City"})
#Html.ValidationMessageFor(model => model.CityId)
</div>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(e) {
$("#State").change(function (e) {
var selectedValue = $(this).val();
if(selectedValue != "Select") {
$.ajax({
url: '#Url.Action("GetCities","Employer")',
type: 'Post',
//data: { "selectedValue": selectedValue},
data: {id: $("#State").val()},
dataType: 'json',
success: function(response) {
var items = "";
$.each(response, function(i, city) {
$("#City").append('<option value="' + city.Value + '">' + city.Text + '</option>');
});
},
error: function (ex) {
alert("Failed To Receive States" + ex);
}
});
}
});
});
</script>
#Html.DropDownListFor(x => x.LeagueId, Model.LeagueSL, "--Select League--", new { id = "ddlLeague"})
#Html.DropDownListFor(x => x.LeagueId, Model.DivisionSL, "--Select Division--", new { id = "ddlDivision"})
The Second DropDownList is empty, all it has is the option Label --Select Division--
On change event of the 1st dropdown make an AjaxRequest that fills the Second One.
var value = $("#DropDown1").val();
var ddlDivision = $("#DropDownDivision");
ddlDivision.html('');//clear current contents;
$.ajax({
url: "/Home/GetDivisions",
type: "GET",
data: { leagueId: value },
success: function (data) {
$.each(data, function (index, item) {
//item = this
//populate ddl
ddlDivision.append($('<option></option>')
.val(item.PropTwo)
.html(item.PropOne));
});
});
public JsonResult GetDivisions(int leagueId)
{
using (BaseballEntities context = new BaseballEntities())
{
var divisions = (from x in context.Table
where x.LeagueID == leagueId
select new
{
PropOne = x.DivisionName,
PropTwo = x.DivisionId
}).ToList();
return Json(divisions, JsonRequestBehavior.AllowGet);
}
}
Edit: As a Side Note it is better to use your Model to fill your dropdownList.
Give your model a SelectList property
public List<SelectListItem> LeagueSL { get; set; }//you will need to initialize in constructor
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
using (MyEntities context = new MyEntities())
{
var leagueList = context.League.ToList();
foreach (var item in leagueList)
{
model.LeagueSL.Add(new SelectListItem() { Text = item.LeagueName, Value = item.LeagueId.ToString() });
}
}
return View(model);
}
Drop down lists are their own beast. You probably need to create the new OPTIONs using standard DOM methods inside the loop rather than jQuery's append method:
success: function(response) {
var items = "", option, $city = $("#City");
$.each(response, function(i, city) {
option = document.createElement("option");
option.value = city.Value;
option.innerHTML = city.Text;
$city.append(option);
});
},