I am trying to create Multilevel Dropdown.
I have default dropdown with values
Ex. Parent Dropdown with Id='ddl1'
If we select value from it then load data from server with selected and Create new dropdown name as child dropdown, and again select value from child and load data from server, if data present then create child dropdown.
we have to create drowpdown, till n level.
'Ex. i am creating like below'
function createdropdown(id) {
var labelHtml = "<tr id='trFormType" + id + "' class='trFormType'><td><label class='tdLabel'>" + labelFormType + " * </label></td>";
labelHtml += "<td><select class='ddlFormType' id='ddlFormType" + id + "' name='ddlFormType" + id + "' >";
labelHtml += "<option value=''";
labelHtml += ">" + labelSelect + "</option>";
labelHtml += "</select></td></tr>";
return labelHtml;
}
var selectedId=''; $(".ddlFormType").live("click", function () { selectedId= "#" + $(this).prop('id'); });
$(selectedId).live("change", function () { $.ajax({ url: Url + 'Method/' + (selectedId).val(), type: 'GET', dataType: 'json', cache: false, timeout: 9000, success: function (data) { $("#detailTable tbody").append(createdropdown(currentId)); }
});
'But .change event not get fired, for dyncamically created dropdown'
'Hope you can understand?'
For creating n level dropdowns you need to create a dropdown in ajax callback like this:
$.ajax({
url: "Your URL",
method: "GET",
dataType: 'json',
success: function (data) {
$("Your Dropdown Conatiner").append("<select><option name="option1" value="1"></option>...</select>");
},
error: function (data) {
}
});
It think your problem is that you are creating the select after the DOM has been fully loaded and jQuery has already registered all events.
If you want to add dinamically N selects you should include a call to register it inside the code you are adding to the DOM, check this sample:
<div id="select-container"></div>
<script>
function CreateSelect(id){
return `<select id="ddl` + id + `">
<option value="Opcion">Opcion<\/option>
<option value="Opcion2">Opcion 2<\/option>
<\/select>
<script>
RegisterSelectChangeEvent(` + id + `);
<\/script>`;
}
function RegisterSelectChangeEvent(id){
console.log("Event Raised");
$("#ddl" + id).on("change", function (e) {
jQuery("#select-container").append(CreateSelect(id+1));
});
}
(function(){
jQuery("#select-container").append(CreateSelect(1));
})();
</script>
You can see it working here:
https://codepen.io/anon/pen/LQRqYY
Related
I know this question has been asked many times but no matter what i try i just can't get it to work. I have an actionResult that accepts three parameters and returns a partial view. Now what i want to do is take the values of three elements and re-render the view in a div using them. I have tried to use the captured data to render the div succesfully but i can't figure out what i'm doing wrong with jquery
In the script file are included the last things i tried(although in every attempt there was some tweaking before giving up)
Here is the RenderAction in the main view (that works)
<div id="tables">
#{ Html.RenderAction("_Tables", new { date = "5/10/2019", time = "13:00", seats = "1" });}
</div>
the action result that returns said Partial
public ActionResult _Tables(string date, string time, int seats)
{
return PartialView("_Tables", checkTables(date,time,seats));
}
And finally the script(searchTable is a button near the fields. Their values are captured succesfully but load does not work)
$('#searchTable').click(function () {
var date = document.getElementById("datepicker").value;
var time = document.getElementById("time").value;
var seats = document.getElementById("seats").value;
alert(date);
//var data = JSON.stringify({
// 'date': date,
// 'time': time,
// 'seats': seats
//});
//$.ajax({
// type: "POST",
// url: '/Home/_Table/',
// data: data,
// dataType: "html",
// success: function (result) { success(result); }
//});
//function success(result) {
// alert(result);
// $("#tables").html(result);
// $("#tables").load("#tables")
//};
//$.ajax({
// url: "/Home/_Table",
// type: "GET",
// contentType: "application/json; charset=utf-8",
// data: data,
// success: function (data) {
// $('#target').html(data); // loading partialView into div
// }
//});
//$('#tables').load('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
$('#tables').load('#Url.Action("_Tables","Home")', { 'date': date, 'time': time, 'seats': seats });
alert(time);
//alert('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
});
I know the problem lies in my lack of understanding but i do not have the time to research ajax. My internship is based on "figuring it out" under deadlines"
Suppose you have a div with id tables as
<div id="tables">
You can use the following method of appending the partial view content based on your paramters as
$.ajax({
url: "/Home/_Tables?date=" + val + "&time="+ val +"&seats="+seats,
type: "POST",
cache: false,
success: function (result) {
$("#tables").empty();
$("#tables").html(result);
},
error: function () {
$("#tables").empty();
}
});
this will be the main view ajax function.and in the controller do the following
public ActionResult _Tables(string date, string time,string seats)
{
// here you can provide model,any viewbag values etc to the partial view and you will get corresponding html result
return PartialView("Yourpartial ViewName");
}
I see a commented line in your code :
$("#tables").html(result);
It's all you need!
You should fill your div with all partial view html that returns from your controller.
I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),
I am having gridview showing data from database such as
ProductID ProductName Price
----------------------------------
A00001 Apple 10.00 ADDTOCART
The ADDTOCART is a button.
GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
string itemId = gr.Cells[0].Text.Trim();
These are the code I use for codebehind to get the ProductID when click on ADDTOCART
Need assist for the code which can let the variable I declared in Jquery to get the ProductID like what the codebehind do when I click the ADDTOCART button.
function ShowCurrentTime() {
var name = "The name";//$("#<%=txtUserName.ClientID%>")[0].value; //get the data.
var id = "The id";//$("#<%=TextBox1.ClientID%>")[0].value; //get the data.
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
function OnSuccess(response) { //fetching object come out, object inside got name and id, need to specific which data you want by obj.id/obj.name
var obj = response.d; //fetching the webmethod
alert(obj.id + "" + obj.name) //display the return
$('#trycart').append("<li>" + obj.id + "</li>");
$('#cart').append("<tr><td>" + obj.id + "</td><td>" + obj.name +"</td></tr>"); //access the table id=cart, add in the data comeback from webmethod.
}
I need assist to have the var name to have the product name, and var id to have the id when I click ADDTOCART.
The element name and selectors can be manipulated by looking at the Dom.
In the button onclick pass this as parameter
function ShowCurrentTime(element)
{
var name = $(element).closest("tr").find("input[id*='txtUserName']").val();
var id = $(element).closest("tr").find("input[id*='TextBox1']").val();
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
I guess that Your data from database is in your C# application, which is on your server side. The code above are jquery/javascript, which is on your client side.
It's very important to know the difference on server side and client side. Basically say, everything you can see from "view source" from browser, are client side, otherwise, on server side.
So go back to your question, you can build html with data from database in your c# application, or build json data object, and in turn use it in jquery.
Hope helps
I'm having a problem with some JavaScript which is intended to display a JQUERY dialog box based on a C# ViewModel.
I have an ASP drop down within a repeater which displays 'Registration Date' information. The idea is when the user selects a date from the list, the JavaScript dialog box will appear displaying a more rounded summary of information relating to that registration using specific View Model properties. The function CustomerSummary is called on a standard $(document).ready for the page in question.
JS Code
function CustomerSummary() {
var registrationId;
var data;
$("select[id$='ddlRegistration']").change(function () {
registrationId = $(this).val();
if (registrationId !== 'default')
{
data = MakeAJAXCall(registrationId);
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
"Permit From: " + data.PermitFrom + "<br />" +
"Permit To: " + data.PermitTo + "<br />" +
"Registration Status: " + data.RegistrationStatus
);
$("#dialog").dialog({
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
}
});
function MakeAJAXCall(regId)
{
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "text json",
url: "/Secure/CustomerSummary.aspx/GetRegistration",
data: "{ regId: \"" + regId + "\" }",
success: function (msg) {
data = msg.d;
},
error: function (xOptions, textStatus)
{
console.log(textStatus);
console.log(xOptions);
}
});
}
}
C# Code
[WebMethod(), ScriptMethod(UseHttpGet=false)]
public static RegistrationViewModel GetRegistration(int regId)
{
RegistrationRepository repo = new RegistrationRepository();
RegistrationViewModel reg = new RegistrationViewModel();
RegistrationFactory regFac = new RegistrationFactory();
reg = regFac.ConvertToRegistrationViewModel(repo.GetRegistration(regId));
return reg;
}
What is happening during debug
What is happening here is on this line :
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
I'm getting the error:
Uncaught TypeError: Cannot read property 'RegistrationId' of undefined
The first time I select a date from the menu and the change function is invoked, I get the above error message, and no dialog box appears, if I inspect data I can indeed see that it is undefined. Then, once I select a different data from the drop down menu, and I hit my breakpoint (change.(function) data is set to the data retrieved from the previous AJAX call, the dialog box then pops up but with the previous requests data, the results then stay in this cycle, every time I select a data I am presented with the previous selections information.
Can anyone point out why im constantly one selection out of sync, I believe its due to the first change request but I don't understand why the AJAX call isn't setting data to the desired result until I select the next drop down item.
This will not work
data = MakeAJAXCall(registrationId);
Because MakeAJAXCall is performing an Ajax call and it is asynchronous so the return will not execute in the same order as your return in the function. So, you need to use a callback.
Try this to change your code to something like:
MakeAJAXCall(registrationId, function(data){
$("#dialog").html("Registration Id: " + data.RegistrationId + "<br />" +
"Permit From: " + data.PermitFrom + "<br />" +
"Permit To: " + data.PermitTo + "<br />" +
"Registration Status: " + data.RegistrationStatus
);
});
Then on your Ajax Call you need to make this change as well:
function MakeAJAXCall(regId, callback)
{
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "text json",
url: "/Secure/CustomerSummary.aspx/GetRegistration",
data: "{ regId: \"" + regId + "\" }",
success: function (msg) {
data = msg.d;
callback(data); //<--- You callback function is called here
},
error: function (xOptions, textStatus)
{
console.log(textStatus);
console.log(xOptions);
}
});
}
First A in Ajax is for asynchronous. It means your call will run in the background and that is why you use callbacks. When your call completed with success/error, say 10 seconds later, correct function is called. In the meanwhile, you other code that sets up and creates a result also runs, most likely before any answers received from ajax query. As #Dalorzo suggested, wrap your result dialog code in a callback, so your code will run after results received.
I'm implementing multiple autocomplete using jQuery UI. Also I'm using webservice to pass values. I check jQuery UI demo for multiple autocomplete and using exact same code and it's working until the first autocomplete and adds a "," at the end.
But here I'm stuck, It's not searching for the next autocomplete. Well I didn't add a part of the code from the demo, which I don't know where it suppose to go. If someone could help me please.
Heare isthe My code
<script type="text/javascript">
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".tb")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//term: extractLast(request.term),
response($.map(data.d, function (item) {
return {
value: item.Email
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
search: function () {
// custom minLength
var term = extractLast(this.value);
alert(term);
if (term.length < 2) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
alert(terms);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
} //,
//minLength: 2
});
});
</script>
Here is the code I'm missing from jQuery UI demo
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
I don't know where to add this code:
term: extractLast( request.term )
here is the link for entire code Demo Code link
replace
data: "{ 'mail': '" + request.term + "' }"
with
data: "{ 'mail': '" + extractLast(request.term) + "' }"
this should work but i didn't like much the way you encode JSON, may create problems with quotes etc.