I have 2 dropdown. States/Divisions and Townships. Townships dropdown is blank. If I choose something in the S/D dropdown, Township dropdown changes according to the S/D selection. But I can't see the dropdown list in the Township and it's just white. Can someone help me please?
It's work but the changes in township dropdown list are blank.
My controller
[HttpGet]
public JsonResult Township_Filter(string id)
{
List<string> tsp = db.TB_Township.Where(t => t.StateDivisionID.Equals(id)).Select(t => t.Township).ToList();
return Json(tsp, JsonRequestBehavior.AllowGet);
}
My Ajax call
$(document).ready(function () {
$("#StateDivision").on("change", function () {
var sdID = $("#StateDivision").val();
$.ajax({
type: 'GET',
url: '/LoanMaster/Township_Filter',
data: {id : sdID},
beforeSend: function(){
},
success: function (tsp) {
if(tsp != null)
{
$('#Township').empty();
$('#Township').append($('<option value="">--Choose--</option>'));
for (i = 0; i < tsp.length; i++)
{
$('#Township').append($('<option value="' + tsp[i] + '>"' + tsp[i] + '</option>'));
}
}
},
complete: function () {
}
});
});
});
My View
<select id="StateDivision" class="form-control">
<option>--Choose--</option>
<option value="100">A</option>
<option value="101">B</option>
</select>
<select id="Township" class="form-control abc">
<option>--Choose--</option>
</select>
There is a syntax error
$('<option value="' + tsp[i] + '>" ' + tsp[i] + '</option>')
maybe that's why. try This
$('<option value="' + tsp[i] + '">' + tsp[i] + '</option>')
Related
I call an MVC controller via Java and AJAX. The data goes to the controller, the controller returns a List. How do I access that list? This may seem trivial, but I can't find it anywhere on google or SO. Most of the examples I've found call for using:
...
success: function (r) {
var exemptions = r.d;
...
for (var i = 0; i < exemptions.length; i++){
ddlist.appent('<option>' + exemptions[i] + '</option>');
....
}
That method, however, results in this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (6:281)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Controller Method:
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The dropdown box:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetGoodRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The JavaScript/AJAX query:
<script type="text/javascript">
function GetGoodRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var exemptions = response.d;
var ddlist = $('#dd');
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
for (var i = 0; i < exemptions.length; i++) {
ddlist.append('<option>' + exemptions[i] + '</option>');
}
}
});
};
</script>
Can anyone spell this out to me in layman's terms?
Regards,
Carthax
Give this a shot in your success function:
success: function (response) {
for (var i = 0; i < response.length; i++) {
var obj = JSON.parse(JSON.stringify(response[i]));
alert(obj.Text);
}
}
This will show an alert of what is contained in each object of the response array.
(In case someone happens upon this question in google)
Based on input from #MikeMarshall, here is the solution that works:
The controller action is correct, but I'm putting it all in one place so you don't have to copy-and-paste from all over the page
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The razor code:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The script:
<script type="text/javascript">
function GetRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// get the dropdownlist
var ddlist = $('#dd');
// empty the dropdownlist and add "Select Exemption"
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
// for each value in the response
for (var i = 0; i < response.length; i++) {
// properly query the Value and Text fields in the array
ddlist.append('<option value="' + response[i].Value + '">' + response[i].Text + '</option>');
}
}
});
};
</script>
I have made two multiselect dropdown using multiselect js plugin.
2nd dropdown gets populated on the option selection of 1st dropdown. I have use ajax for this purpose. But on ajax callback, 2nd dropdown elements are not getting clear, and new options are not populating.
This is my html code:
<div class="row col-md-6" >
<select id="multidropdown" multiple="multiple" onchange="ChangedView()">
#foreach (var item in clients)
{
<option value=#item.ToString() class="col-md-5"> #item.ToString() </option>
}
</select>
</div>
<div class="row col-md-6" id="ProgramsDiv">
<select id="programIDs" multiple="multiple" onchange="SelectSensorsFromPrograms()">
#foreach (var item in programs)
{
<option value=#item.ToString() class="col-md-5"> #item.ToString() </option>
}
</select>
</div>
and this is my JavaScript code:
function ChangedView()
{
$(".mtable").remove();
var multiclients = $("#multidropdown option:selected").text();
var program = $("#programIDs option:selected").text();
var sensors = $("#sensorIDs option:selected").text();
var request = $.ajax({
url: '#Url.Action("GetselectedProgramClient")',
type: 'POST',
data:
{
"ClientNames": multiclients
},
dataType: 'json',
success: function (data)
{
debugger;
if (data.length > 0)
{
$('#programIDs').html('');
var options = '';
console.log(data.length+"\n");
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i] + '">' + data[i] +" " + '</option>';
console.log(options);
}
$('#programIDs').append(options);
$('#programIDs').multiselect('rebuild');
}
},
error: function (xhr) {
console.log("Error: " + xhr.statusText);
if (xhr.statusText == 'error') {
return;
}
else if (xhr.statusText == 'OK') {
return;
}
}
});
}
Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}
I have a Select2 list and added multiple items to the table.But i wanted to check if items already exists in the table or not first and IF not only then add new item But below my code doesn't work.
In this code everytime it shows Not Found & add duplicate rows
HTML Part
<select id="select-product" multiple style="width: 300px">
</select>
Code
$("#select-product").change(function () {
debugger;
var $option = $('#select-product option');
if ($("#select-product option[value='ProductCode']").length > 0) {
alert("Found");
}
else
{
alert("Not Found");
}
$option.each(function () {
if ($(this).is(':selected')) {
debugger;
var itm = $(this).is(':selected');
var temp = $(this).attr('ProductCode');
var row = '<tr>';
row += '<td class="itmcode">' + $(this).attr('ProductCode') + '</td>';
row += '<td class="itmname">' + $(this).text().replace(temp, " ") + '</td>';
row += '<td class="unit">' + $(this).attr('Unit_UnitId') + '</td>';
row += '<td class="retprice" dir="rtl" align="right">' + $(this).attr('RetailPrice') + '</td>';
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="' + $(this).val() + '" data-prod-id="' + $(this).attr('Value') + '">' + '</td>';
row += '<td class="col-md-1 disc" dir="rtl">' + '<input type="text" class="input-disc form-control input-sm">' + '</td>';
row += '<td class="tot" dir="rtl" align="right">0</td>';
row += '<td class="imgdel"><img class="btn-img-del" src="../Images/delete.png" alt="" title="Delete" /></td>';
row += '</tr>';
table.append(row);
}
});
$('#select-product').select2('data', null);
});
Multiple Products Code
function CallMultipleProducts() {
$.ajax({
type: "POST",
url: '/Sales/GetMultipleProducts',
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
debugger;
if (msg._productlist.length > 0) {
debugger;
$.each(msg._productlist, function (index, item) {
debugger;
$('#select-product').append($("<option></option>")
.attr("Value", item.ProductId)
.attr("RetailPrice", item.RetailPrice)
.attr("ProductCode", item.ProductCode)
.text((item.ProductCode) + " " + (item.ProductName))
);
});
}
}
// error: AjaxError
})
}
Make sure that you have only select item with unique id="select-product" throughout your html.
Try below code, use .find()
if ($("#select-product").find("option[value='ProductCode']").length > 0) {
alert("Found");
}
Please try adding the below option to your select2 options if the element is input type="text",
$("#select-product").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
If you are using <select> element, I'm afraid you can't use this option. You have to use input instead. You might find something useful here.
look at this code :
[WebMethod]
public static string GetFacilities(string id)
{
int hotelid = System.Convert.ToInt32(Tools.DecryptString(id));
string ret = "";
foreach (var item in new FacilityGroupBL().Load())
{
if(item.Facilities.Count != 0)
{
ret += "<fieldset>";
if (item.Facilities.Count() != 0)
{
foreach (var subitem in item.Facilities)
{
if (subitem.HotelFacilities.Where(obj => obj.HotelId == hotelid).Count() != 0)
ret += "<input type='checkbox' checked='false' />" + subitem.Name;
else
ret += "<input type='checkbox' checked='true' />" + subitem.Name;
}
}
else
{
ret += "There is no facility in this fieldset.";
ret += "</fieldset>";
}
}
}
return ret;
}
by this code i load some checkboxes in a DIV,then user change some checkboxes and press the SAVE button.at this time ,i should send the values of these checkboxes to server to update my data in database.by i dont know how?:( please help
note: my default code for this probem is here but it does not work($("#FacilitiesDIV input[type=checkbox]").serializeArray() is empty)
$.ajax({
type: "POST",
url: "HotelsList.aspx/SaveFacilities",
data: "{ 'id' : '" + $("#HiddenField").val() + "', 'Facilities' : '" + $("#FacilitiesDIV input[type=checkbox]").serializeArray() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function () {
$('#dialogMessage').dialog('open');
$('#dialogMessage span').html("Operation Error");
}
});
$("#FacilitiesDIV input[type=checkbox]").serializeArray() since you are referring element using "#" then you need to give the fieldset element an Unique ID assuming you have
html like
<fieldset> <input type='checkbox' checked='false' /> some text
<input type='checkbox' checked='false' /> some text
</fieldset>
set the id to element <fieldset id = 'FacilitiesDIV'>
I believe it should work if you give each checkbox a name, ie:
<input type='checkbox' checked='false' name="mycheckboxes" />