mCustomScrollbar not working on jquery append - javascript

In my html i am trying to update the cart data via ajax calls.
In html
<div id="cart_list"></div>
And inside script
$(document).ready(function(){
jQuery.get("/show_header/",
function(data) {
show_cart(data)
});
})
And this is the show_cart function
function show_cart(data){
$("#cart_list").append(
'<div class="dropdown cartMenu ">'+
''+
'<div class="dropdown-menu col-lg-6 col-xs-12 col-md-6 " style="width: 184%;">'+
'<div id="scroll_cart" class="w100 miniCartTable scroll-pane">'+
'<table>'+
'<tbody>'+
cart_string+
'</tbody>'+
'</table>'+
'</div>'+
'<div class="miniCartFooter text-right">'+
'<h3 class="text-right subtotal"> Subtotal:₹ '+ data.header_data.price +' </h3>'+
'<a class="btn btn-sm btn-danger" href="/cart/"> <i class="fa fa-shopping-cart"> </i> VIEW CART </a>'+
' CHECKOUT </div>'+
'</div>'+
'</div>'
)
}
(cart_string is generated inside function show_cart. But i removed those steps since i think its not relevant here).
But the scrollbar is not working anymore. I tried the other answers in this section and nothing seems to work.
I tried giving the div with the scroll class an id "scroll_cart" and tried the following line inside show_cart function. But no change.
$("#scroll_cart").mCustomScrollbar("update");
What is the right way to enable scrollbar for the div?

You need to use $("#scroll_cart").mCustomScrollbar("update"); after creating the elements.
ie, after show_cart() function.
Because the element $("#scroll_cart") should be present on the dom at the time of binding.
$(document).ready(function() {
jQuery.get("/show_header/",
function(data) {
show_cart(data);
$("#scroll_cart").mCustomScrollbar("update");
});
})

please see this reference
codes:
$('#scroll_cart').mCustomScrollbar("destroy");
$('#scroll_cart').append('some text');
$('#scroll_cart').mCustomScrollbar();

please make sure in your HTML file you have included jquery.mCustomScrollbar.concat.min.js

Related

Unable to find the specific items value jQuery

I am facing an easy problem but unable to find a solution the problem is
i am creating a dynamic div with some elements also with some data
$("#divSearchedIssue").append(`
<div class="statistic d-flex align-items-center bg-white has-shadow">
<div class="icon bg-red">
<i class="fa fa-tasks"></i>
</div>
<div class="text">
***//want to get this below id value//**
Mobile Code :
<small id="mbCode">
${ data[0].MobileCode }
</small>
***/want to find/**
<br>
Failed From:
<small>
${ data[0].FailedStation }
</small>
<br>
Issues :
<small>
${ data[0].Issues }
</small>
</div>
<div class="text"><strong> </strong></div>
<div class="text">
<button type="button" id="btn" class="btn btn-warning pull-right">Start</button>
</div>
<div class="text"><br></div>
</div>`);
Here I have a button .On this button click i want to fetch the value of
small text which id is #mbCode as mentioned above inside the code
I am trying this by using the following button click code
$(document).on('click', '#btn', function () {
var data = $(this).closest('small').find('#mbCode').val();
alert(data);
});
but its not working.I mean I cant fetch the value of #mbCode on this button click .So help needed
Thanks for helping
Based on .closest()
Description: For each element in the set, get the first element that
matches the selector by testing the element itself and traversing up
through its ancestors in the DOM tree.
As <small> is not an ancestors to button in hierarchy(while traversing-up),
So You need to first go the parent of <small> through .closest() and then try to find <small> html using .find() and .html()
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').html();
alert(data);
});
Working snippet:-
data = [{'MobileCode':20,'FailedStation':'WATERLOO','Issues':'broken'}];
$("#divSearchedIssue").append('<div class="statistic d-flex align-items- center bg-white has-shadow"><div class="icon bg-red"><i class="fa fa-tasks"></i></div><div class="text">Mobile Code :<small id="mbCode">' + data[0].MobileCode + '</small><br>Failed From: <small> ' + data[0].FailedStation + '</small><br>Issues :<small> '+ data[0].Issues + '</small></div><div class="text"><strong> </strong></div><div class="text"><button type="button" id="btn" class="btn btn-warning pull-right">Start</button></div><div class="text"><br></div></div>');
$(document).on('click', '#btn', function () {
var data = $(this).closest('.statistic').find('small').each(function(){
alert($(this).html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Note:- .text() will work too
https://jsfiddle.net/tyz4ox50/
As identifiers must be unique, Directly use ID Selector with .text()/.html() method
var data = $('#mbCode').text()
However if you are appending multiple elements I would recommend an alternative to persist Mobile code arbitrary data using custom data-* attribute along with <button> which can be fetched using .data(key) and attach event handler using Class Selector
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + data[0].MobileCode + '" >Start</button>');
var counter = 0;
function append() {
$("#divSearchedIssue").append('<button type="button" id="btn" class="btn btn-warning pull-right" data-mobilecode="' + ++counter + '" >Start</button>');
}
append();
append();
append();
$(document).on('click', '.btn', function() {
var data = $(this).data('mobilecode');
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
Try the following code snippet
var value = $('#mbCode').val();
Make sure the id is unique
Ids shouldn't be duplicate in an web-page.
Also, small is not one of the parent nodes of btns, and use html instead of val.
You need to go two-level higher to statistic Make it
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
Demo
var counter = 0;
function append() {
$("#divSearchedIssue").append(
`<div class="statistic d-flex align-items-
center bg-white has-shadow">
<div class="icon bg-red"><i class="fa fa-tasks">
</i></div>
<div class="text">
Mobile Code :<small id="mbCode">` +
(counter++) +
`</small><br>Failed From: <small> ' +
data[0].FailedStation + '</small><br>Issues :<small> ' + data[0].Issues +
'</small></div>
<div class="text"><strong> </strong>
</div>
<div class="text"><button type="button" id="btn" class="btn btn-
warning pull-right">Start</button></div>
<div class="text"><br></div>
</div>`
);
}
append();
append();
append();
$(document).on('click', '.text #btn', function () {
var data = $(this).closest('.statistic').find('#mbCode');
console.log(data.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divSearchedIssue"></div>
If your element already has an ID attribute you should be able to find the element by the ID. $("#mbCode")
Your js code
$(this).closest('small').find('#mbCode').val(); // "$(this)", in your code, represents the "button" that was clicked.
is looking for "small" tag inside "button" element, but it's not there. It would work if your button was like
<button type="button" id="btn" class="btn btn-warning pull-right"><small id="mbCode"></small></button>
This should work:
$(document).on('click', '#btn', function () {
var $mbCode = $('#mbCode');
console.log($mbCode);
});

Load Modal dialog by injecting HTML with JQuery

I have the following function on my JS file that has defined the HTML code for a Modal dialog that is defined in here
I've copied the HTML code and assigned into a variable on my JS function:
function loadModalDialog(p1) {
var modal = '<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
' <div class="modal-header">' +
' <button type="button" class="close" data- dismiss="modal" aria- hidden="true" >×</button>' +
' <h3 id= "myModalLabel"> Modal header </h3>' +
' </div>' +
' <div class="modal-body">' +
' <p>One fine body…</p>' +
' </div>' +
' <div class="modal-footer">' +
' <button class="btn" data- dismiss="modal" aria- hidden="true"> Close </button>' +
' <button class="btn btn-primary"> Save changes </button>' +
' </div>' +
'</div>';
}
Also, I have another JS function that calls loadModalDialog but at this point I am not sure how to inject the html that I have on my modal var into the DOM once I am inside of above function so I can display the modal dialog.
BTW, I want to inject the html through the JS function because eventually I will change the body of the dialog and it will change dynamically according p1 value.
BTW, the line of code that is calling loadModalDialog looks like this:
PopUp
Any idea how it should work?
Might be an approach. The trick is to establish a proper selector to wich the dialog() function could be called:
$("<div>Sample of an injected dialog</div>").dialog();
Is't actually very easy if you watch the jquery sample in contrast
$( "#dialog" ).dialog();
You simply replace the selector with concrete text (no meta chars).
If you want to execute a js function right after the dialog has loaded, you inline that function and provide it's parameters via JSON stringification. Like this
$("<div id='difflv2d'></div><script>drawGraph("
+ JSON.stringify(sd.side) + "," + JSON.stringify(sd.id) + ","
+ JSON.stringify(sd.title) + "," + JSON.stringify(sd.num) + ","
+ JSON.stringify(sd.data) + ")</script>").dialog();
In the sample above, the drawing function selects the div given by id 'difflv2d' and puts its stuff onto it. Since the div already is part of the dialog (just loaded), the graphic appears on that dialog. Stuff to draw is read out of the variables provided properly.
Here is a reference: on the fly div

How to get JSP parameter in dynamically? (or create JSP parameter)

I'm new to JSP and ajax but trying both at the same time.
I'm making a dynamic tab that can be added or removed with these steps.
I wannna put parameter from controller in the newly added tab's content area.
1.When a 'Load Project' button from the list is clicked, add a new tab.
$('<li role="presentation">'
+'<a href="#'+tabId+'" aria-controls="'+tabId+'" role="tab" data-toggle="tab">'
+$projectName
+' <span class="closeTab glyphicon glyphicon-remove" aria-hidden="true"></span>'
+'<input class="hiddenProjectId" type="text" name="projectId" value="'+ pId +'" style="display: none;">'
+'</a></li>').insertBefore('#liProjectTabAdd');
$('<div role="tabpanel" class="tab-pane fade" id="'+ tabId + '">'
+ '<div class="projectContent">'
+ '<ul class="blockList list-unstyled draggableList"></ul>'
+ '<div class="table-hover addBlock">'
+ 'add block <span id="addBlockGlyp" class="glyphicon glyphicon-plus" aria-hidden="true"></span>'
+ '</div></div>'
+ '</div>').appendTo('.projectTab-content');
2.call the controller through ajax(post method)
$.post("loadProjectContent.do",
{
projectId: pId
}
);
3.The controller call DAO and get the project's content.
(The contents are correct. I checked it with printing)
Project project = new Project();
project.setProjectId(Integer.parseInt(request.getParameter("projectId")));
dao.doGetProjectContent(project);
request.setAttribute("projectContent", project.getProjectContent());
Then now, how to get this projectContent in JSP?
I've tried adding jsp tag when I append the tab, but it was a raw text.
(like ~~~${ projectContent }~~~)
$('<div role="tabpanel" class="tab-pane fade" id="'+ tabId + '">'
+ '<div class="projectContent">'
+ '<ul class="blockList list-unstyled draggableList">'
+ '${ projectContent }'
+ '</ul>'
+ '<div class="table-hover addBlock">'
+ 'add block <span id="addBlockGlyp" class="glyphicon glyphicon-plus" aria-hidden="true"></span>'
+ '</div></div>'
+ '</div>').appendTo('.projectTab-content');
Please save this newbie
Write the projectContent to the response instead of adding it as a request attribute.
On the client side, parse the response of your AJAX request and add it to the DOM.

JQuery: Unable to get property from each img in a list of images

I'm trying to create a snippet of HTML, and iterate through each image within that snippet and apply a listener function and modify the image. However, using JQuery's .each() function is not allowing me to use functions such as .prop() to get/set image attributes. How can I apply functions such as .prop() to elements iterated over by the .each() function.
//formatImg simply returns a URL to the resource
var images = '<div class="flex-row">\
<div class="img">\
<img class="img-cover" data-src="' + formatImg(gallery.posts[0].image, 'medium') + '">\
</div>\
<div class="img">\
<img class="img-cover" data-src="' + formatImg(gallery.posts[1].image, 'medium') + '">\
</div>\
</div>';
var location = gallery.posts[0].location.address || 'No Location';
var elem = $('<div class="col-xs-6 col-md-3 tile story">\
<div class="tile-body">\
<div class="frame"></div>\
<div class="hover">\
<p class="md-type-body1">' + (gallery.caption || '') + '</p>\
<ul class="md-type-body2">\
<li>' + gallery.posts.length + (gallery.posts.length == 1 ? ' photo' : ' photos') +'</li>\
</ul>\
</div>\
' + images + '\
</div>\
<div class="tile-foot">\
<div class="hover">\
See all\
<!--<span class="mdi mdi-library-plus icon pull-right"></span>-->\
<!--<span class="mdi mdi-download icon toggle-edit toggler pull-right"></span>-->\
</div>\
<div>\
<div class="ellipses">\
<span class="md-type-body2">' + location + '</span>\
<span class="md-type-caption">' + getTimeAgo(new Date().getTime(), gallery.time_created) +'</span>\
</div>\
</div>\
</div>\
</div>'
);
elem.find('img.img-cover').each(function(){
_this = $(this);
console.log(_this.prop('data-src'));
attachOnImageLoadError(_this);
_this.prop('src',_this.prop('data-src'));
});
The console.log(_this.prop('data-src')) from within each, it returns undefined for every image.
Your problem has nothing to do with each(). Your problem is that you're trying to use prop() to handle HTML5 data attributes.
"data-src" is not an HTML property, therefore _this.prop('data-src') returns null. You would run into the same problem if you were using prop() to try to write to a data-src attribute.
Instead, to read a data attribute named data-src using jquery, use data(). So use _this.data('src').
See https://api.jquery.com/data/#data-html5 for more help.
I have created a simple script below that may help you to make it work:
var images = '<div class="flex-row">\
<div class="img">\
<img class="img-cover" data-src="img-1" />\
</div>\
<div class="img">\
<img class="img-cover" data-src="img-2">\
</div>\
</div>';
$(images).find('img.img-cover').each(function() {
alert($(this).data('src'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to add repetitive div with jQuery?

When I click on the new button with jQuery it adds the div, but it only adds one. When I check from DevTools it constantly creates the same place. But I want it to add another one after that. Can you help me?
HTML code
<div class="text-left" style="margin-bottom: 15px;">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone"></div>
Here are the sample js codes
$('.add-extra-email-button').click(function() {
var element = $('.clone');
element.html(
'<div class="clone_edilen_email">' +
'<li>' +
'<a href="javascript:;"> Test' +
'<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i>' +
'</a>' +
'</li>' +
'</div>'
);
$('.clone_edilen_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
$(document).on('click', '.remove-field-email', function(e) {
$(this).parent('.btn-delete-branch-email').parent('.remove-email').remove();
e.preventDefault();
});
If I understand correctly, you want to add the <div class="clone_edilen_email"> again and again, as soon somebody clicks on the .add-extra-email-button button.
In general, calling element.html('<some_wild_html></some_wild_html>') will always override the full inner content of element with <some_wild_html></some_wild_html>. Also, if the element already contains some other sub-elements, they will got lost. In your given code example, I assume, your intention was to extend the element's html and not replace it.
Here is my suggestion:
$('.add-extra-email-button').click(function() {
var newDiv = $('<div class="clone_edilen_mail"></div>');
newDiv.html('<li><a href="javascript:;"> Test<i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i></li>');
$('.clone').append(newDiv); // This is the important clue here!
// afterwards you may insert your residual class stuff
// $('.clone_edilen_email').addClass('single-email remove-email'); <- I would suggest you add these classes already at the begining, where I set the variable "newDiv"
// ...
// $('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
// $('.clone_edilen_email > .single-email').attr("class", "remove-email");
});
// .. your other code may follow here ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clone">I am a clone-div!</div>
<button class="add-extra-email-button">Click Me!</button>
Hope that this might help you!
Try This Method, Append Duplicate Elements and Contents Using jQuery .clone() Method
<!doctype html>
<html>
<head>
<title>jQuery Clone() – Add Elements and its Contents</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<style>
div {
margin:3px;
padding:3px;
border:solid 1px #999;
width:300px;
}
</style>
</head>
<body>
<p>Click the button to clone (make a duplicate) of the DIV element!</p>
<div id="Container">Hello, how was your day!</div>
<p><input type="button" id="Button1" value="Clone it" /></p>
</body>
<script>
$(document).ready(function () {
$('#Button1').on('click', function () {
$('#Container')
.clone()
.appendTo("body");
});
});
</script>
</html>
In your first click function you replace all the content of your div clone so even if you click again you are going to have only one. He is just replacing the old one.
I didn't get what you are trying to do with the second click function.

Categories