how to dynamically create a dropdown menu? - javascript

I have no problem creating the menu dynamically.
My problem : the class submenu is not working. I assume it's because the alert doesn't appear.
When I hard code the li´s and do not create them dynamically, the submenu works.
I'm using .NET
<script type="text/javascript">
jQuery(document).ready(function () {
mostrarGrupo01();
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
});
function mostrarGrupo01()
{
var k = 0;
var grupo01;
$.ajax({
type: "POST",
url: "Mesa.aspx/getGrupo01",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
grupo01 = response.d;
$('#grupos').empty();
$.each(grupo01, function (index, BEGrupo) {
//var r = $('<input type="button" value="' + BEAreaCC.DSAREACC + '" id="' + BEAreaCC.CDAREACC + '" name="' + BEAreaCC.CDAREACC + '" style="font-size:xx-large" onclick="botonClick(this.id, this.name, this.title);"/> ');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '" onclick="mostrarGrupo02(this.name, this.id);">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
var t = $('<li class="submenu">' + BEGrupo.DSGRUPO01 + '</li>');
$('#grupos').append(t);
k++;
});
},
failure: function (msg) {
$('#grupos').text(msg);
}
});
}
</script>
HTML :
<div class="contenedorMenu">
<nav class="menu">
<ul id="grupos">
</ul>
</nav>
</div>

The HTML element with class submenu is added to your page dynamically. You therefore need to bind your event in the following way:
$(".submenu").on('click',function () {
alert("hola");
$(this).children("ul").slideToggle();
});

You are binding the click event before .submenu is added to the DOM due to the asynchronous nature of $.ajax.
You have two options:
1 . Bind you click event within the .ajax success callback after you add the .submenu elements to the DOM
success: function (response) {
...
$.each(grupo01, function (index, BEGrupo) {
...
});
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
},
2. Or change your click binding to target the parent ul
$("#grupos").on('click', '.submenu', function () {
alert("hola");
$(this).children("ul").slideToggle();
})

Related

Get jQuery dropdown value onchange event

I load partialview on load page .
$(window).bind("load",
function() {
$.get("/agent/GetInfo",
function(data) {
$("#home-tab-right").empty();
$("#home-tab-right").append(data);
});
});
I have a dropdown on partialview. I want to run a function on change it. I use this code but don't run it.
$(document).ready(function(){
$('#StateId').change(function() {
var item = $(this).val();
$.ajax({
url: '#Url.Action("FindCity", "Agent")',
type: 'POST',
data: { value: item },
success: function(result) {
$("#CityId").find('option').remove();
$.each(result,
function(i) {
var optionhtml = '<option value="' +
result[i].Id +
'">' +
result[i].Name +
'</option>';
$("#CityId").append(optionhtml);
});
$(".popup-loading").hide();
}
});
});
});
In order to avoid attaching the same event multiple times. Use Off() first
$(document).off("change.findCity").on("change.findCity","#StateId",function(){ //process })
<script type="text/javascript">
$(document).ready(function (event) {
$('#StateId').on('change', function (event) {
//do something
});
});
</script>

Ajax request called multiple times though I need only once?

I have been working on a e-commerce web application. There is a wishlist module which I'm trying to implement. I'm adding the products into wishlist using ajax calls and also removing it with ajax. The adding part works fine but I have a problem in removing part . What I'm trying to do is, making an ajax call to fetch the wishlist items from the database and adding a remove button dynamically using jquery. Although I know that I have to use a .live function to attach an event to it which I did but when i click on the button all the items which are present in the wishlist are removed . I see multiple ajax request was made in console under network tab and I don't get it why , although I clicked it only once. The following is a snippet of my code
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a id='remove' href='#'>REMOVE</a></div>");
foo(value['id']);
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
}
});
function foo(value) {
var pid = value;
$('#remove').live("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
In the first ajax request I'm fetching products from the database then adding remove button to it dynamically then calling function foo which attach the click event using .live function and then make call to database to remove it.
Hey guys I'm not pro at web, so go easy on me if I made some silly mistake.
Thanks!
Problem:
You have same id for multiple hyperlink and you are using .live function on "id based" selector. It is applying click function again & again on first element.
Solution:
Update your hyperlink
<a href='#' onclick="foo(this)" pid=value['id']>REMOVE</a>
Then in foo() function
function foo(obj) {
var pid = $(obj).attr("pid");
$(obj).bind("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
i don't get why you using same id multiple times.
and afaik, jQuery.live already deprecated.
you can use this if you want to get live behavior:
$(document).on('click', 'element-selector', function(){
...
});
with your code, it can rewriten to:
$(document).on('click', '[id=remove]', function(){
...ajax call...
});
now the problem with your fetch data function is this:
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
...append element...
**foo(value['id']);**
} else {
...append element...
}
});
as we know foo() are your function that bind remove behavior.
based on your code, whenever that fetch data has newVar = 1, it will directly call foo. which mean binding remove behavior multiple times, as many as newVar = 1 was.
solution:
you can put pid as a attribute on your a element
maybe something like remove
and within remove click function, you can use $(this).attr('pid') to get that value.
and remove that foo() content to outside the function, since $(element).live(...) or $(document).on(event, element, ...) will listen the element, even the element dynamicly added to the page.
The issue happened because you register listener multiple times in each loop. So to resolve, you need to register once after all button has been populated. I also change selector to class ".remove" because you going to have multiple remove button so using id is will be duplicated, and using jquery .on() instead of .live() (deprecated)
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a class='remove' id='remove' data-pid='" + value['id'] + "' href='#'>REMOVE</a></div>");
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
foo();
}
});
function foo() {
$('.remove').on("click", function() {
var pid = $(this).data("pid");
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});

Select option does not show data

This is my first attempt to databind an html control via ajax. I check/debug my ajax call and the data are retrieved OK, but the do not appear in the select option. My javascript is located at the bottom of my aspx page. What's the problem
$(function () {
$.ajax({
type: "POST",
url: "psHlp.asmx/getDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#District").empty();
$.each(msg.d, function () {
$("#District").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load districts");
}
});
});
This is my select option which is located at the beginning of my page
<div class="col-sm-3 col-xs-12 ffield">
<select id="District" style="display: none;">
</select>
</div>
Try using like this on your each loop.
var options;
$.each(msg.d, function () {
options += '<option value="' + this["Value"] + '">' + this["Text"] + '</option>';
});
console.log(options);
$("#District").append(options);
You need to specify (index,value) params in your $.each callback function and use value to access the iterated elements. Something like this.
$.each(msg.d, function (index,value) {
$("#District").append("<option value='" + value.Value + "'>" + value.Text + "</option>");
});
Finally I found the solution. All the above suggestions were correct. The problem occurred because I'm using bootstarp js/css (customer's designer provided the layout), so I need to rebuild the multiselect option after the append.
var options = "";
$.each(response.d, function () {
options += '<option value="' + this['Value'] + '">' + this['Text'] + '</option>';
});
$("#Town").append().html(options);
$("#Town").multiselect('rebuild');
Hope this will help at least one person :)

Bind textbox with response from onclick event - jquery

I have a textbox in my view page. when i click on imageIcon,it will take data from db and return in alert successfully. But, when i try to bind this response data to textbox, it is not binded correctly. My code in view page is as following :
#foreach (var dateitem in list)
{
<td id="HoursTxt">
#Html.TextAreaFor(modelitem => dateitem.Hours, new { id = string.Format("txtHours"), style = "width:50%;height:70%;" })
#Html.Hidden("CuDate", dateitem.Date)
<img src="~/Images/comment.png" class="prevtest" />
<div style="border:solid;display:none;">
<input type="text" id="TxtNotess" />
<input type="button" id="BtnComment" value="Save" />
</div>
</td>
}
In my onclick event of imageIcon jquery is following:
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId =parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
success : function(data)
{
alert(data);
$('#TxtNotess').val(data);
alert('success');
},
error:function()
{
alert('Error');
}
});
$(this).next().toggle();
});
the text box with id TxtNotess not bind with response value
Can anyone help me to do this..
Thanks in advance..
First: ID of an element must be unique so use class for the textfield TxtNotess.
<input type="text" class="TxtNotess" />
Then, in the success handler find the textfild with class TxtNotess inside the next sibling of the clicked element
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$(this).next().find('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
$('.prevtest').on('click', function () {
var Cudate = $(this).prev('#CuDate').val();
var ProjId = parseInt($(this).parents('tr').find('input[type="hidden"]').val());
var TskId = parseInt($(this).parents('tr').find('td').find('#testTaskId').val());
$.ajax({
type: "POST",
url: "/Timesheet/GetComments?ProjectId=" + ProjId + "&TaskId= " + TskId + "&date= " + Cudate,
context: this,//pass a custom context to the ajax handlers - here the clicked element reference
success: function (data) {
alert(data);
$('.TxtNotess').val(data);//find the target textfield
alert('success');
},
error: function () {
alert('Error');
}
});
$(this).next().toggle();
});
I gets resolved by using class name for textbox..

How to load JSON data associated with each link onclick?

I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.

Categories