Deleting only one link which should be removed from list - javascript

HTML
<a href="/portfolio/${portfolio.id}" data-portfolio-id="${portfolio.id}" data-bookmark-id="${bookmark.id}" class="ac-hns">
<span>${portfolio.title}</span>
<span>By ${portfolio.ownerName}</span>
<img src="${portfolio.coverImage()}" alt="">
</a>
<a href="/portfolio/${portfolio.id}" data-portfolio-id="${portfolio.id}" data-bookmark-id="${bookmark.id}" class="ac-hns">
<span>${portfolio.title}</span>
<span>By ${portfolio.ownerName}</span>
<img src="${portfolio.coverImage()}" alt="">
</a>
JS
$('.ac-hns').on('click', '.icn-close-white', function (e) {
e.preventDefault();
deleteBookmarkItem( $(this), $(this).parent().attr('data-portfolio-id'), $(this).parent().attr('data-bookmark-id') );
});
function deleteBookmarkItem( btn, itemID, bookmarkID ) {
$.ajax({
url: '/api/bookmarks/'+ bookmarkID,
type: 'DELETE',
success: function( response ) {
$('.ac-hns').remove();
console.log('delete portfolio from bookmark');
}
});
}
The items are dynamic via json. If delete one of items on the list, say 3 items under one same bookmark, one item should be removed under the same bookmark and it wouldn't be on same bookmark anymore.
But right now, click on close icon on one of the items, all the items are removed under the same bookmark which is not right.
Help or insight appreciated.
Update
Just realize - could remove data-bookmark-id="${bookmark.id}" from tag and it won't appear in the bookmark list. I tried removeData('data-bookmark-id'), but it doesn't take bookmark id out.

$('.ac-hns').remove(); in the callback is removing everything with that class. Hard to tell with your HTML structure but I think you want something like this:
function deleteBookmarkItem( btn, itemID, bookmarkID ) {
$.ajax({
url: '/api/bookmarks/'+ bookmarkID,
type: 'DELETE',
success: function( response ) {
$('[data-bookmark-id="'+bookmarkID+'"]').remove();
console.log('delete portfolio from bookmark');
}
});
}

Because $('.ac-hns').remove(); removes all element with class .ac-hns.
You have to specify on your script which element with class of .ac-hns should be removed.
And since you want to change the whole group, it's parent including other child elements, do this $(itemID).remove();
Edit: also $(this).parent().attr('data-portfolio-id') when you pass as parameter, remove the .attr so it will only pass the parent and thus when you $(itemID).remove();, the script will able to know which parent it is then remove that element including its children.

Related

Ajax jQuery Multiple Step Form instead of reloading div, just append new content

I wonder if it's possible to do this multistep form on one single page, so not reloading the div with the content received from the php file but append it right below..
This is what I've got so far:
$(document).on('submit', '#reg-form', function(){
var ln = $('#submit').val();
var id = $('#id').val();
var data = 'submit='+ln;
$.ajax({
type: 'GET',
url : 'step.php',
dataType : 'html',
data : data,
success : function(data)
{
$('#reg-form').fadeOut(500).hide(function()
{
$('.result').fadeIn(500).show(function()
{
$('.result'+id).append(data);
});
});
}
});
return false;
});
Also I tried to use different divs, with incremental id's to put every content in it's own div. The Problem is, I'm only getting the "second" step, so it's not going through the whole formular.
I guess it's because the form of the first page is still there and all have the same id.. Can anyone help me out here please?
id of element in document should be unique. Change the duplicate id at html source or using javascript
success : function(data) {
// change duplicate `reg-form` `id` to value
// corresponding to `.length` of elements having `id`
// containing `"reg-form"`
$(data).filter("#reg-form")
.attr("id", "reg-form-" + $("[id*='reg-form']").length);
$("#reg-form").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result" + id).append(data);
});
});
}

Make an array with all classes of an SVG element

I know this may look like a repost, but I am not able to get the code to work that the community made here.
What I am trying to do is make an array of all the classes listed in the element I am clicking on.
The element I am clicking on is a <g></g> element from a SVG object.
I would like to post the classes (in an array) to a modal and the ID of the <g> element. Here is my code:
//reveal Modal when when clicking on an item box.
$(document).ready(function() {
$('.items').click(function() {
$.ajax({
type: "POST",
url: "/includes/functions/choose_item.php",
data: { id: this.id, class: this.className}
})
.done(function() {
$('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ;
})
});
});
It post it to my PHP script, and the ID works, but the class is in an array of baseval and animval, and I would like an array of all values of the baseval only.
This is the array I get:
Array ( [animVal] => items hero_item [baseVal] => items hero_item )
Thanks for any help.
SVG elements doesn't really have classes like regular elements, and the className property returns a special object, usually a SVGAnimatedString looking like
{animVal: "class class2", baseVal: "class class2"}
The class attribute is really just a regular attribute with some strangeness, so you need to use getAttribute('class') instead, or in jQuery attr() to get the value of the attribute
$(document).ready(function() {
$('.items').click(function() {
$.ajax({
type : "POST",
url : "/includes/functions/choose_item.php",
data : {
id : this.id,
'class' : $(this).attr('class')
}
}).done(function() {
$('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ;
});
});
});
note that class is a keyword in javascript, so it should be quoted.
If you need an array, you can do $(this).attr('class').split(/\s+/);
TEST

jquery what the best way to reset every positioning to default?

I have a few thumbnails upon clicked, it will display all the works of the user, for example user 1 have 1 work, user 2 have 6 works. By right i will be showing the div accordingly to how many works the user have. If i click on user 1, it show 1 work, i exit and click on user 2, instead of 6 works it show 1 only, because the function takes on what was set on user1, as i didn't reset.. So i wonder if there is a best practices for resetting the show/hide div back to default upon exit, the only solution i know of now is calling the .show each time the function activates, but doesn't seem to be a good way to do things. Please advise
Example
$(function() {
$(".img_thumb_holder").on('click', function() {
var index = $(this).index(); // get current index of clicked thumbnail, so i can call out the related name from captionArray via same index
// what i did to solve the reseting, forcing it to show out each time the function runs
$(".portfolio_thumbImg_holder").show();
$.ajax({
type: "POST",
dataType: "json",
data: ({id: idArray[index]}), // pass the name of clicked holder into php to query
url: "CMS/PHP/retrieveAuthorWorks.php",
success: function(data) {
console.log("Array consist of " + data)
$('.portfolio_thumbImg_holder img').removeAttr("src");
linksArray=[];
titleArray=[];
descArray=[];
$(".full_image_desc .title").html(data[0].title);
$(".full_image_desc .info").html(data[0].desc);
$('.portfolio_thumbImg_holder img').each(function(index, element) {
if (data[index]) {
linksArray.push("http://localhost/testdatabase/cms/" + data[index].links);
$(element).attr("src", linksArray[index]);
titleArray.push(data[index].title);
$(element).attr("title", titleArray[index]);
descArray.push(data[index].desc);
$(element).attr("desc", descArray[index]);
}
});
// check how many divs without the image data, and hide it
$(".portfolio_thumbImg_holder img:not([src])").parent().hide();
}
});
});
});

RactiveJS Should Target The Element Triggering Proxy Event, Not It's Children

I'm trying to add an active classname to the li that is clicked on. Showing that it's selected.
My template:
var legCatagoryTemplate = "<ul>{{#legs:i}}<li><a href='#' on-click='selectCategory:{{this}},{{i}}' data-id='{{i}}'><figure><div class='imgWrapper'><img src='{{preview}}'></div><figcaption><h4>{{name}}</h4><p>W: {{width}}" H:<span></span>: {{material}}</p></figcaption></figure></a></li>{{/legs}}</ul>";
How its called:
var legCategoryView = new Ractive({
el: "#catalog",
template: legCatagoryTemplate,
data: response_from_ajax
});
How I'm handling the event:
legCategoryView.on('selectCategory', function ( event, self, index ){
console.log(event.target, self, index);
}
What I've found:
event.target is the element inside of the a that was clicked (eg div.imgwrapper, figcaption)
Non Ractive behaves similarly: click event on a div should not be triggered by it's children
What is a good solution to targeting the element with the on-click proxy object?
You might just traverse the DOM and find the li element but that can cause troubles in certain situations. If you call ractive.set('legs', new_data), Ractive will reuse the existing nodes, so your class will remain there. There are several solutions for this problem (the third is probably the best):
Use ractive.merge() instead of ractive.set().
Use splice() and push() instead of ractive.set().
Change your template and let Ractive manage the class:
<ul>
{{#legs:i}}
<li class="{{#.active }}active{{/}}">
<a href='#' on-click='selectCategory:{{this}},{{i}}' data-id='{{i}}'>
<figure>
<div class='imgWrapper'><img src='{{preview}}'></div>
<figcaption>
<h4>{{name}}</h4>
<p>W: {{width}}" H:<span></span>: {{material}}</p>
</figcaption>
</figure>
</a>
</li>
{{/legs}}
</ul>
ractive.on('selectCategory', function ( e ) {
ractive.set(e.keypath + '.active', true);
});
I just had the idea of using jQuery to traverse up the dom with $.closest() like this
legCategoryView.on('selectCategory', function ( event, self, index ){
$(event.original.target).closest('li').addClass("active");
}
That works actually.

does jquery html result replace targeted div or append content

From javascript function on success action I'm injecting content to div using it's id.
$.ajax({
url: formatUrl('/MyController/MyActionMethod'),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id: target }),
success: function (result) {
$("#myPopUp").html(result);
$("#myPopUp").popup("open");
},
error:...
});
on Layout.cshtml view page I have div
<div id="myPopUp" data-role="popup">
Close
</div>
Popup renders content fine, but without close button on popup window.
My question is: If I send result to the #myPopUp from javascript do I overwrite Close content since it is under <div id="myPopUp" .. /> tag.
.html() is going to overwrite the < a > dom element.
.append() will add it to #myPopUp so that it is a sibling of the < a > element.

Categories

Resources