Removing Element from String Template - javascript

I have a JavaScript string called _categoryItemDivTemplate that defines HTML markup, including a <div> with class="MakeTopLevelCategory".
I thought I can remove that <div> with the following code:
item = $(_categoryItemDivTemplate);
if (!isTopLevel)
item.remove('div.MakeTopLevelCategory');
But it has no effect.
Am I missing something? Is it necessary to first add the item to the DOM?
EDIT:
Here's the template from the code:
var _categoryItemDivTemplate =
'<div class="CategoryItem" style="clear:both;">'
+ '<div class="CategoryHeader">'
+ '<img src="/images/plus.gif" class="Icon"/>'
+ '<img src="/images/icn_folder.gif" class="Icon"/>'
+ '<span class="Title"> </span>'
+ '<div style="float:right; font-size: 11px;" class="CategorySelector">'
+ '<div class="DeleteCategory" title="Delete this Category"> </div>'
+ '<div class="EditCategory" title="Rename this Category"> </div>'
+ '<div class="MakeTopLevelCategory" title="Make this Category a Top-level Category">&nbsp</div>'
+ '<div class="MoveSubcategory" title="Move this Category"> </div>'
+ '<div class="SubcategoryMarker AddSubcategory" title="Add a new Subcategory to this Category"> </div>'
+ '<div class="PackageCostingMarker AddPackage" title="Add a new Package to this Category"> </div>'
+ '<div class="ProductCostingMarker AddProduct" title="Add a new Product to this Category"> </div>'
+ '<div class="NarrativeMarker AddArticle" title="Add a new Article to this Category"> </div>'
+ '</div>'
+ '</div>'
+ '<div class="CategoryItems" style="display: none;">'
+ '</div>'
+ '</div>';

Removing it from the object does not removes it from the string, if you want to remove it from the string then you need to replace the string with the object sources so try
item = $('<div />', {html:'_categoryItemDivTemplate'});
if (!isTopLevel) {
item.find('div.MakeTopLevelCategory').remove();
}

Related

How to dynamically add form elements in jquery?

I'm trying to created a dynamic form in rails with a little bit of javascript I have a problem I only get one row in the output when using pry apparently it's because I have the same params for every field input since I use jQuery .clone, maybe someone has struggled with something similar can share some knowledge, how to dynamically add index to params in this form with javascript ?
#extends('Admin.master')
#section('content')
<div class="p-5">
<h3><i class="fas fa-cog ml-2"></i>Setting</h3><hr>
<form action="{{ route('settings.update', $setting->id) }}" method="POST" >
#csrf
#method('PUT')
<div id="showDynamic">
</div>
</form>
</div>
#endsection
#section('script')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
let count = 1;
$('.add').click(function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary" id="add">Add</a>\n' +
'<a class="btn btn-danger" id="delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
#endsection
1st id must be unique .. So change id="add" and id="delete" to classes class="btn btn-primary add"
2nd event-binding-on-dynamically-created-elements After changing the id to class use $(document).on('click' , '.add' , function(){ //code here })
Your code should be
<script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showDynamic"></div>

dynamically Created html link does not work [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
After creating a batch of Html nodes, The link does not work!
How can I fix it?
Javascript Codes:
var nnn = '<div class="media mt-3 w-100" id="commentNode_0000">' +
'<a class="pr-0" href = "#" >' +
'<img class="mr-3" src="/images/comment1.png" alt="x">' +
'</a>' +
'<div class="media-body w-100">' +
'<h5 class="mt-0 mb-1">User</h5>' +
'<div id="collapse_0000" class="">' +
'<div id="cardId_0000" class="card">' +
'<p>TEST TEST</p>' +
'</div>' +
'<div class="comment-meta" id="commentId_0000">' +
'<span><input id="deleteC_24_20" type="submit" class="submitLink" value="delete"></span>' +
'<span><input id="editC_24_20" type="submit" class="submitLink" value="edit"></span>' +
'<span>' +
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>' +
'</span>' +
'<div id="replyComment_0000" class="collapse"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$(collapseId).append(nnn);
Exactly this line of code:
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>'
I expect this event to fire after clicking the tag that I have created dynamically.
But it doesn't work!
$("a[id^='replyC_']").on("click", function (event) {
var nodeId = event.target.id;
});
var collapseId = document.getElementById('collapseId')
var nnn = '<div class="media mt-3 w-100" id="commentNode_0000">' +
'<a class="pr-0" href = "#" >' +
'<img class="mr-3" src="/images/comment1.png" alt="x">' +
'</a>' +
'<div class="media-body w-100">' +
'<h5 class="mt-0 mb-1">User</h5>' +
'<div id="collapse_0000" class="">' +
'<div id="cardId_0000" class="card">' +
'<p>TEST TEST</p>' +
'</div>' +
'<div class="comment-meta" id="commentId_0000">' +
'<span><input id="deleteC_24_20" type="submit" class="submitLink" value="delete"></span>' +
'<span><input id="editC_24_20" type="submit" class="submitLink" value="edit"></span>' +
'<span>' +
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>' +
'</span>' +
'<div id="replyComment_0000" class="collapse"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$(collapseId).append(nnn);
$("a[id^='replyC_']").on("click", function (event) {
var nodeId = event.target.id;
console.log(nodeId);
});
<div id="collapseId"></div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
it works fine :)

send data from form with <li> attributes

My data in my form will be inserted by javascript. These are li attributes. I want to send the data in these li attributes to an other php page. But that's not possible?
function addProduct() {
//var productid = document.getElementById('product').value;
var product = products[type];
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
var productAdded = $('<li class="product" name="product' + i + '">' +
'<div class="product-image">' +
'<a href="image">' +
'<img src="images/' + product + '.jpg" alt="placeholder"></a>' +
'</div>' +
'<div class="product-details">' +
'<a style="color: black;">' + product + '</a>' +
'<span class="price">€ ' + price + '</span><br>' +
'<div class="quantity">' +
'<label>Aantal: ' + qty + '</label> <div class="actions">' +
' <a href="#0" class="delete-item" >Delete</a></div></div></div></li>');
cartList.prepend(productAdded);
}
<div class="cd-cart">
<div class="wrapper">
<header>
<h2>Winkelkar</h2>
<span class="undo">Verwijder product. Ongedaan maken</span>
</header>
<div class="body">
<form id="formtosubmit" class="form-style-12" action="checkout.php" method="post">
<ul name="products">
<!-- products added to the cart will be inserted here using JavaScript -->
</ul>
</form>
</div>
<footer>
<a id="checkoutbtn" class="checkout btn" onclick="document.getElementById('formtosubmit').submit()"><em>Ga verder: €<span>0</span></em></a>
</footer>
</div>
</div>
You can create <input type='hidden'/> element in between those <li> tags and write each product ID or product name to the value of that <input> tag. This way when you submit your form, those values will be captured.
EX:
function addProduct() {
var productid = document.getElementById('product').value;
var product = products[type];
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
var productAdded = $('<li class="product" name="product' + i + '">' +
'<div class="product-image">' +
'<a href="image">' +
'<img src="images/' + product + '.jpg" alt="placeholder"></a>' +
'</div>' +
'<div class="product-details">' +
'<a style="color: black;">' + product + '</a>' +
'<span class="price">€ ' + price + '</span><br>' +
'<div class="quantity">' +
'<input type="hidden" value="'+productid+'" readonly name='productid[]'>' +
'<label>Aantal: ' + qty + '</label> <div class="actions">' +
' <a href="#0" class="delete-item" >Delete</a></div></div></div></li>');
cartList.prepend(productAdded);
}
Now you may have noticed what is that name='productid[]' in input tag? That means create an array of every input value particular to that element. More information can be found here.
Another approach would be saving your selected product IDs into a cookie/session variable. Then your server side can access that information and process the cart accordingly. If you were to delete a product from the cart then make sure you update your session/cookie value as well.

facebook like photo viewer jQuery FBPhotoBox

Creating A Image Viewer with Descriptions Like Facebook - jQuery FBPhotoBox
everything is working good but i could not retrive image name, description and album name
$(document).ready(function() {
$(".fbphotobox img").fbPhotoBox({
rightWidth: 360,
leftBgColor: "black",
rightBgColor: "white",
footerBgColor: "black",
overlayBgColor: "#1D1D1D",
onImageShow: function() {
$('.imgtitle').html($(this).attr("data-title"));
$('.imgdesc').html($(this).attr("data-desc"));
}
});
});
show: function(image) {
if (image.attr("fbphotobox-src")) this.tempImage.src = image.attr("fbphotobox-src");
else this.tempImage.src = image.attr("src");
$(".fbphotobox-tag").remove();
var index = this.targetObj.index(image);
this.leftArrow.attr("data-prev-index", index-1);
this.rightArrow.attr("data-next-index", index+1);
if (index-1 < 0) this.leftArrow.hide();
else this.leftArrow.show();
if (index+1 >= this.targetObj.length) this.rightArrow.hide();
else this.rightArrow.show();
},
html code
<div class="fbphotobox">
<img src="museumgallery/<?php echo $setdetail['image'] ?>" class="img-polaroid" width="190" id="<?php echo $setdetail['id'] ?>" data-title="<?php echo $setdetail['itemname'] ?>" data-desc="<?php echo $setdetail['description'] ?>"/>
</div>
and the viewer is appended as
['<div class="fbphotobox-main-container">',
'<div class="fbphotobox-container-left">',
'<table class="fbphotobox-main-image-table"><tr><td>',
'<div class="tag-container"><img class="fbphotobox-main-image" src=""/></div>',
'</td></tr></table>',
'<div class="fbphotobox-image-stage-overlay">',
'<div class="fbphotobox-container-left-header">',
'<a title="Full Screen" class="fbphotobox-fc-btn fbphotobox-a"></a>',
'</div>',
'<div data-prev-index="" class="left-arrow">',
'<table style="height:100%"><tr><td style="vertical-align:middle;">',
'<a class="fbphotobox-a" title="Previous"></a>',
'</td></tr></table>',
'</div>',
'<div data-next-index="" class="right-arrow">',
'<table style="height:100%;"><tr><td style="vertical-align:middle;">',
'<a class="fbphotobox-a" title="Next"></a>',
'</td></tr></table>',
'</div>',
'</div>',
'</div>',
'<div class="fbphotobox-container-right">',
'<div class="fbphotobox-close-btn">',
'<a title="Close" href="" style="float:right;margin:8px">',
'<img src="./assets/images/close.png" style="height:10px;width:10px"/>',
'</a>',
'<div style="clear:both"></div>',
'</div>',
'<div class="fbphotobox-image-content">',
'<h3 class="imgtitle"></h3>',
'<div class="imgdesc"></div>',
'</div>',
'</div>',
'<div style="clear:both"></div>',
'</div>',
'<div class="fbphotobox-fc-main-container">',
'<div class="fbphotobox-fc-header">',
'<div style="float:left"></div>',
'<a class="fbphotobox-fc-close-btn" href="">Exit</a>',
'<div style="clear:both"></div>',
'</div>',
'<div style="position:fixed;top:0px;right:0px;left:0px;bottom:0px;margin:auto;">',
'<table style="width:100%;height:100%;text-align:center;">',
'<tr>',
'<td class="fc-left-arrow" style="width:50px;text-align:center;">',
'<a class="fbphotobox-a" title="Previous"></a>',
'</td>',
'<td>',
'<img class="fbphotobox-fc-main-image" src=""/>',
'</td>',
'<td class="fc-right-arrow" style="width:50px;text-align:center;">',
'<a class="fbphotobox-a" title="Next"></a>',
'</td>',
'</tr>',
'</table>',
'</div>',
'<div class="fbphotobox-fc-footer"><div style="clear:both"></div></div>',
'</div>',
'<div class="fbphotobox-overlay"></div>',
'<div style="clear:both"></div>'];
but it appears to be like in this image
http://i.stack.imgur.com/5wFoS.jpg
http://www.jqueryscript.net/lightbox/Creating-A-Image-Viewer-with-Descriptions-Like-Facebook-jQuery-FBPhotoBox.html
this is the link where i got file from
what i am stuck at is i tried
$('.imgtitle').html($(this).attr("data-title"));
$('.imgdesc').html($(this).attr("data-desc"));
to show in the viewer but it only shows src not data-desc or data-title... and also i want to display the album name too
Documentation is bad, but if you examine the code you will see this part:
initDOM: function() {
var html = ['<div class="fbphotobox-main-container">',
'<div class="fbphotobox-container-left">',
'<table class="fbphotobox-main-image-table"><tr><td>',
'<div class="tag-container"><img class="fbphotobox-main-image" src=""/></div>',
'</td></tr></table>',
'<div class="fbphotobox-image-stage-overlay">',
'<div class="fbphotobox-container-left-header">',
'<a title="Full Screen" class="fbphotobox-fc-btn fbphotobox-a"></a>',
'</div>',
'<div data-prev-index="" class="left-arrow">',
'<table style="height:100%"><tr><td style="vertical-align:middle;">',
'<a class="fbphotobox-a" title="Previous"></a>',
'</td></tr></table>',
'</div>',
'<div data-next-index="" class="right-arrow">',
'<table style="height:100%;"><tr><td style="vertical-align:middle;">',
'<a class="fbphotobox-a" title="Next"></a>',
'</td></tr></table>',
'</div>',
'<div class="fbphotobox-container-left-footer">',
'<div style="margin:20px;">',
'<span style="font-weight:bold;">Dummy Photo Caption</span>',
'<span style="color:#B3B3B3;"> in </span>',
'<span style="font-weight:bold;">Dummy Album Name</span>',
'</div>',
'</div>',
'<div class="fbphotobox-container-left-footer-bg"></div>',
'</div>',
'</div>',
'<div class="fbphotobox-container-right">',
'<div class="fbphotobox-close-btn">',
'<a title="Close" href="" style="float:right;margin:8px">',
'<img src="./images/close.png" style="height:10px;width:10px"/>',
'</a>',
'<div style="clear:both"></div>',
'</div>',
'<div class="fbphotobox-image-content"></div>',
'</div>',
'<div style="clear:both"></div>',
'</div>',
'<div class="fbphotobox-fc-main-container">',
'<div class="fbphotobox-fc-header">',
'<div style="float:left">Dummy Header</div>',
'<a class="fbphotobox-fc-close-btn" href="">Exit</a>',
'<div style="clear:both"></div>',
'</div>',
'<div style="position:fixed;top:0px;right:0px;left:0px;bottom:0px;margin:auto;">',
'<table style="width:100%;height:100%;text-align:center;">',
'<tr>',
'<td class="fc-left-arrow" style="width:50px;text-align:center;">',
'<a class="fbphotobox-a" title="Previous"></a>',
'</td>',
'<td>',
'<img class="fbphotobox-fc-main-image" src=""/>',
'</td>',
'<td class="fc-right-arrow" style="width:50px;text-align:center;">',
'<a class="fbphotobox-a" title="Next"></a>',
'</td>',
'</tr>',
'</table>',
'</div>',
'<div class="fbphotobox-fc-footer">Dummy Footer<div style="clear:both"></div></div>',
'</div>',
'<div class="fbphotobox-overlay"></div>',
'<div style="clear:both"></div>'];
$("body").append(html.join(""));
this.settings.afterInitDOM();
},
and at far end we can see that you can define in settings afterIntitDOM() callback function. There you can change your popup template in general, or the Album name this way:
afterIntitDOM: function() {
$('.fbphotobox-container-left-footer span:last').text('My Album name');
}
But since you also want to change the image name and description, than you should use onImageShow method/callback in settings, but there is a problem: this inside is the image in focus, not the original image in DOM tree. So, I suggest you change core show method and add one line at the end of function:
show: function(o) {
/* o is a jQuery object, the original image we need */
....
....
if ( typeof this.settings.myShow==='function' ) this.settings.myShow(o);
}
Then define your myShow callback in settings:
$(".fbphotobox img").fbPhotoBox({
rightWidth: 360,
leftBgColor: "black",
rightBgColor: "white",
footerBgColor: "black",
overlayBgColor: "#1D1D1D",
myShow: function(image) {
var myTitle = image.data('title');
var myDescription = image.data('description');
var myAlbum = image.data('album');
$('.fbphotobox-container-left-footer span:first').html( myTitle );
$('.fbphotobox-container-left-footer span:last').html( myAlbum );
$(".fbphotobox-image-content").html( myDescription );
}
});
This assumes you work with this HTML:
<div class="fbphotobox">
<img data-title="Title 1" data-description="Desc 1" data-album="Album 1" fbphotobox-src="http://lorempixel.com/400/200/fashion/3" src="http://lorempixel.com/400/200/fashion/3" />
<img data-title="Title 2" data-description="Desc 2" data-album="Album 2" fbphotobox-src="http://lorempixel.com/500/300/food/2" src="http://lorempixel.com/500/300/food/2" />
<img data-title="Title 3" data-description="Desc 3" data-album="Album 3" fbphotobox-src="http://lorempixel.com/600/400/transport/1" src="http://lorempixel.com/600/400/transport/1" />
</div>
Working Fiddle/Example here

document.getElementById is returning null on the button click

I have a textarea and a button. The button submits the data to a page through AJAX through a function. When the button is clicked it calls a function that takes in 3 parameters for this question only one of them is necessary.
Let's look at the code to understand more clearly:
var offers = <? php echo PostOffer::GetOffers($_GET["id"]); ?> ;
for (var i = 0; i < offers.length; i++) {
var date = offers[i].Date.split(" ");
document.write('<div class="row-fluid offer">' +
'<div class="span2">' +
'<img class="profile_picture" src="' + offers[i].Picture_Path + '" />' +
'</div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="username">' +
'<p style="font-weight: bold;">' + offers[i].Name + '</p>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>' +
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
'<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="date">' +
'<p class="pull-right"><strong><span class="muted">Offered on: </span></strong>' + date[0] + '</p>' +
'</div>');
if (offers[i].Username == "<?php echo $_SESSION["
username "]; ?>") {
document.write('<div class="controls pull-right">' +
'Edit ' +
'Delete | ' +
'</div>');
}
document.write('</div>' +
'</div>' +
'</div>' +
'<hr />');
}
The important part is:
...
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>' +
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
'<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
...
The most important is:
...
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
...
In the onclick of that button the function document.getElementById("edited_content") returns a null value. I've tried logging it to the console it prints null. Why is that happening?
Any help would be appreciated!
Because at the point you call document.getElementById("edited_content"), edited_content does not exist.
You are creating it by appending a string, so you'd need to do something like:
// Add the first part
document.write('<div class="row-fluid offer">' +
'<div class="span2">' +
'<img class="profile_picture" src="' + offers[i].Picture_Path + '" />' +
'</div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="username">' +
'<p style="font-weight: bold;">' + offers[i].Name + '</p>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>');
// Now we can get edited_content
document.write('<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ');
// Write the rest of the HTML
document.write('<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="date">' +
'<p class="pull-right"><strong><span class="muted">Offered on: </span></strong>' + date[0] + '</p>' +
'</div>');
P.S. You tagged the question with jQuery - there are much better ways of doing what you are trying to achieve. Better still, use a templating engine.

Categories