I'm working on a medical appointment system and I'm using a jquery function to filter the items in my cascading dropdownlists. Is there a way of writing a 'generic' to handle all the dropdownlists instead of writing the same thing several times?
$(document).ready(function () {
$('#ddlIl').change(function () {
$.ajax({
type: "post",
url: "/Users/GetIlce",
data: { Id: $('#ddlIl').val() },
datatype: "json",
traditional: true,
success: function (data) {
var ilce = "<select id='ddlIlce'>";
ilce = ilce + '<option value="">--Seçin--</option>';
for (var i = 0; i < data.length; i++) {
ilce = ilce + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
ilce = ilce + '</select>';
$('#ddlIlce').html(ilce);
}
});
});
});
I have the following dropdownlists: State, City, Department, Hospital, and Doctor
If you want to wrap the AJAX call in a function to serve all dropdownlists in view, probably this code below apply for them:
/*
* #param url = URL to fetch data (i.e. controller action method
* returning IEnumerable<SelectListItem> or SelectList)
* #param source = source dropdownlist name
* #param target = target dropdownlist name
*/
function cascadeDropDownList(url, source, target) {
$.ajax({
type: 'POST',
url: url,
data: { Id: $('#' + source).val() },
dataType: 'json',
traditional: true,
success: function (data) {
// remove previous option contents first
$('#' + target + ' option').each(function() {
$(this).remove();
});
// add new option contents
var options = '<option value="">--Seçin--</option>';
for (var i = 0; i < data.length; i++) {
options += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
$('#' + target).html(options);
}
});
}
Usage in change event:
$(document).ready(function () {
$('#ddlIl').change(function () {
var url = '/Users/GetIlce'; // recommended: '#Url.Action("GetIlce", "Users")'
var source = $(this).attr('id');
cascadeDropDownList(url, source, 'ddlIlce');
});
});
NB: The function above assumes target dropdownlist has already created in view page and you just want to insert option element values without recreating select element. If you want to create new target dropdownlist instead, modify the function like below:
/*
* #param url = URL to fetch data (i.e. controller action method
* returning IEnumerable<SelectListItem> or SelectList)
* #param source = source dropdownlist name
* #param target = target element (e.g. div)
* #param ddlName = target dropdownlist name
*/
function cascadeDropDownList(url, source, target, ddlName) {
$.ajax({
type: 'POST',
url: url,
data: { Id: $('#' + source).val() },
dataType: 'json',
traditional: true,
success: function (data) {
var ddl = "<select id='" + ddlName + "'>";
ddl += '<option value="">--Seçin--</option>';
for (var i = 0; i < data.length; i++) {
ddl += '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
ddl += '</select>';
$('#' + target).html(ddl);
}
});
}
Usage:
$(document).ready(function () {
$('#ddlIl').change(function () {
var url = '/Users/GetIlce'; // recommended: '#Url.Action("GetIlce", "Users")'
var source = $(this).attr('id');
var target = $('#targetdiv').attr('id');
cascadeDropDownList(url, source, target, 'ddlIlce');
});
});
Working example: .NET Fiddle
Related
I want to know how to bind dropdownlist using ajax get. This is the code, What is wrong?
$("#dropdown").on("click",
function ()
{
$.ajax(
{
url: '#Url.Action("List", "Employee")',
type: "POST",
data: $("#dropdown").serialize(),
success: function (data) {
var org = '<option>Select Organisation </option>';
for (var i = 0; i < data.length; i++) {
org += '<option value="' + data[i].organisationid + '">' +
data[i].organisationname + '</option>';
}
$("#dropdown").html(org);
}
});
Beginner here. How can I make a multi select dynamic dependent to another multiselect. The code below is for when a user select a single value and the values of the other select changes based on the value selected. What I want is when all values are selected the values will display all values of each.
$("#value").change(function () {
var user = $("#users_select").val();
$('#value').empty();
$('#value').append($("<option> </option>"));
for (i = 0; i < jsonResult.length - 1; i++) {
if (jsonResult[i]["value"] == user) {
$('#tasks_select').append($("<option value="+jsonResult[i]
["value"]+">" + jsonResult[i]["value"] + "</option>"));
}
}
});
try like this:
$.ajax({
url: base_url + 'url',
type: "GET",
data: {'id': id},
dataType: 'json',
success: function (data) {
var html = '';
$.each(data, function (key, value) {
html += '<option value="' + value.id + '">' + value.selectname + '</option>';
});
$('#id' + count).html(html).select2();
},
error: function () {
}
});
this is my code to change the drop down list values when the checkbox is checked. I use asp.net mvc framework and java script to call the action. The list of the drop-down should show only the expired medicines when the checkbox is checked. But, it results in (Error: [object:object]). It didn't hit the controller action 'getmedicine'. Can anyone help me?
function GetMedicineList(_isExp) {
var url = "getmedicine";
$.ajax({
url: url,
data: { IsExp: _isExp },
cache: false,
type: "GET",
dataType: "json",
success: function (data) {
var markup = "<option value='0'>Please Select Expired Medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#clientId").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
and in the view,
#Html.CheckBoxFor(m => m.IsExp, new { Id = "isExp", #onchange = "GetMedicineList(this.value);" })
I solved the problem. One error is the action that I use to trigger is not an action result. It is a list. I changed it. I also I have did some changes in js. It works properly now.
var GetMedicine= function () {
var url = UrlMedicine.GetMedicineChecked;
var isExp = $('#isExp').val();
var url = url + '?isExp=' + isExp;
$.get(url, null, function (data) {
{
var markup = "<option value='0'>Please Select Expird medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#medicineId").html(markup).show();
}
});
}
var GetMedicineList = function () {
if ($('#isExp').is(":checked")) {
userMedicineHistory.GetMedicine();
}
}
return {
GetMedicineList: GetMedicineList,
GetMedicine: GetMedicine
};
$(document).ready(function () {
$("#isExp").change(userMedicineHistory.GetMedicineList)
});
Probably a simple fix, The rest of the table is sorted excpet this part here
(right at the top)
The table will work now and again in the right order (data from source does not change) but is really dicey when it does or not
Ideas?
Sam
Heres the code
//first define a function
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(3)").text().trim();
var dataB = $(b).find("td:eq(3)").text().trim();
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url1',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tr ><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url2',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
The sorting as to do with spaces but is also linked to your jquery selector.
As often, array are 0 index based in Jquery, then if you want to sort on your price your 2nd column (0-index based) you need to do as below :
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(2)").text().replace(/\s/g, "");
var dataB = $(b).find("td:eq(2)").text().replace(/\s/g, "");
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
var json = {results:[{price:"$12 .45"}, {price:"$13 .45"}, {price:"$12 .05"}, ]}
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
$("#tableid").append("<tr ><td>section</td><td>no</td><td>" + price);
}
sortTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableid"></table>
`
i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}