Deleting href when clicked on a link (a delete icon) beside it (Javascript help) - javascript

I have a link <a href="#"> and beside that there is a delete png icon (which is also <a href="#"> link.
So what I want is, when clicked on that delete icon, the link <a href="#"> should get deleted with a confirmation window.
So far I have got like,
html:
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
My javascript for data-request
var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
success: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
}
This doesn't seem to be working! When I am clicking on the delete icon, it is displaying the confirmation window but not doing anything.
Is there any other simple way of achieving this? If not, can anyone tell me where am I going wrong?
Thanks.

var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
error: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
this.prev().remove();
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
Note that I had to change success: to error: for demonstration.

Related

How to make links added from JSON clickable?

I am trying to append links from a JSON file but their onClick is not working.
HTML:
<li class="nav-item dropdown" id = "views">
<a class="nav-link dropdown-toggle" id="view-type" data-toggle="dropdown" data-selected="high_level" aria-haspopup="true" aria-expanded="false">High Level View</a>
<div class="dropdown-menu" aria-labelledby="view-type" style="height: 35vh; overflow: auto;">
<h7 class="dropdown-header">View Type</h7>
<a class="dropdown-item filter-option active" href="javascript:void(0);" id="high_level">High Level View</a>
</div>
</li>
Javascript:
d3.json(theURL, function(error, data) {
if (error) throw error;
var unique = [];
data.forEach(function(e){
if(unique.indexOf(e.segment) == -1){
unique.push(e.segment);
}
});
unique.forEach(d =>
$('#views .dropdown-menu').append(`<a class="dropdown-item filter-option ecodes" href="javascript:void(0);" id="${d.substring(0, 4)}">${d}</a>`)
)
if($('#all').hasClass('active') == true) {
$('.ecodes').remove();
}
});
$('.filter-option').on('click', function() {
let text = $(this).text();
let selected = $(this).prop('id');
$(this).parent().parent().children('a').text(text);
$(this).parent().parent().children('a').data().selected = selected;
filters[$(this).parent().parent().children('a').prop('id').replace('-','_')] = selected;
$.each($(this).parent().children('a'), function(i,d)
$(d).removeClass('active'); });
$(this).addClass('active');
});
Is there something wrong with my code? I cant seem to figure out why my links aren't working. I need onClick for them to have the class active.
You should use the static element as a starter then delegating the dynamic node(child node) inside the on method
$('dropdown-menu').on('click','.filter-option', function() {
let text = $(this).text();
let selected = $(this).prop('id');
$(this).parent().parent().children('a').text(text);
$(this).parent().parent().children('a').data().selected = selected;
filters[$(this).parent().parent().children('a').prop('id').replace('-','_')] = selected;
$.each($(this).parent().children('a'), function(i,d)
$(d).removeClass('active'); });
$(this).addClass('active');
});
You have to delegate the click to the parent element that exists in the page before you inject new links.
jQuery's on method accepts a selector as the second argument so you can update the following line:
$('.dropdown-menu').on('click', '.filter-option', function() {
let text = $(this).text();
let selected = $(this).prop('id');
$(this).parent().parent().children('a').text(text);
$(this).parent().parent().children('a').data().selected = selected;
filters[$(this).parent().parent().children('a').prop('id').replace('-','_')] = selected;
$.each($(this).parent().children('a'), function(i,d)
$(d).removeClass('active'); });
$(this).addClass('active');
});
Read more: http://api.jquery.com/on/#direct-and-delegated-events

Laravel not getting redirected properly

In Laravel I have a web Route
Route::get('/signout', 'GlobalController#getLogout');
I use a logout option in my page as
<li>
<a href="{{ url('signout') }}">
<i class="icon-key font-red-thunderbird"></i> Log Out
</a>
</li>
The same way I have a ajax Change password success js script as
function parseError(response)
{
var res = 0;
$.each(response, function(i, item){
$('#'+i+'_message').html(item);
if(item!=1)
$('#'+i+'_message').css('display', (item!=1)?'block':'none');
else
res += parseInt(item);
});
if(res != 0 )
{
bootbox.alert("Password changed successfully..!");
window.location='/signout';
}
}
But the window.location='/signout'; is not touching the function getLogout() but the screen is changing to the login screen.
I have written a set of functions in getLogout which is not executing. What could be the problem.
You should try this:
<script>
// your "Imaginary javascript"
window.location.href = '{{url("yoururl")}}';
</script>
OR
<script>
window.location.href = '{{route("myRoute")}}';
</script>

Knockoutjs binds correctly however href on a tag doesn't redirect to the page

I have this html:
<ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px">
<li role="presentation" data-bind="attr : {'data-id' : ID , 'data-childCount' : Children().length}" style="padding-left: 20px; padding-right: 20px; text-align: center; color: white" class="active-li">
<label id="menu1" data-toggle="dropdown" data-bind="text: Name"></label>
<ul class="dropdown-menu" data-bind="foreach: Children" role="menu" aria-labelledby="menu1">
<li role="presentation"><a role="menuitem" data-bind="text: Name, attr: { 'href': Url} "></a></li>
</ul>
</li>
</ul>
That creates my menu on top using knockoutjs, it works perfectly and href attribute on a tag is filled correctly like href="/site/models#{"catId": "76b4a8ed-1350-46af-8184-3b68029cbd22"}" however when i click on the item, it doesn't redirect to new page. my first thought was maybe its because of hash but it wasn't, so i tried to use target attribute for any of the _self and all others it doesn't work. so my next guess was that there is a javascript method overriding this, so far i haven't found anything. so my question is why doesn't it work?
KnockOut ViewModel:
landing.dataModels.Category = function (_id, _categoryTypeId, _name, _description, _parentId, _children) {
var self = this;
this.ID = ko.observable(_id);
this.CategoryTypeId = ko.observable(_categoryTypeId);
this.Name = ko.observable(_name);
this.Description = ko.observable(_description);
this.ParentId = ko.observable(_parentId);
this.Url = ko.computed(function () {
return '/site/models#{"catId": "' + self.ID() + '"}';
});
this.Children = ko.observableArray([]);
this.getChildren = ko.computed(function () {
return self.Children();
});
_.each(_children, function (item) {
self.Children.push(new landing.dataModels.Category(item.ID, item.categoryTypeId, item.Name, item.Description, item.ParentId, item.Children));
});
};
Update
I have to say that when i right-click on the item and open in new window it does work and shows the page, but its not working on direct left click.
Probably the problem is in the quotes in the generated URL:
href="/site/models#{"catId": "76b4a8ed-1350-46af-8184-3b68029cbd22"}"
The value for href is actually "/site/models#{" leaving the rest of the URL as invalid HTML.
You could try to bind to the escaped URL:
this.Url = ko.computed(function () {
return encodeURI('/site/models#{"catId": "' + self.ID() + '"}');
});
Finally i got tired and i just went with a simple jquery click to make it work:
$(document).ready(function () {
setTimeout(function () {
$(document).on("click", ".ilia-catLink", function () {
var a = $(this).attr("href");
window.location = a;
});
}, 100);
It works this way, but i still wonder why wouldn't that href work on itself.

How to get which link has been clicked in jquery

Good day...
I have multiple links as below:
<li>Save</li>
<li>Save As</li>
<li>Save And Exit</li>
I wanna know which link has been clicked
I tried something like this:
if ($("#mmSaveForm").click() == "true") {
//do something
}
else if ($("mmSaveAs").click() == "true") {
//Do something
}
else if ($("#mmSaveExit").click() == "true") {
//Do something
}
I tried these links, questions & answers but they are not helping:
How can I get the button that caused the submit from the form submit event?
jQuery: how to get which button was clicked upon form submission?
how to detect which button is clicked using jQuery
jQuery - how to determine which link was clicked
I've been trying this the whole night, please help...
Thank you in advanced...
Why don't you target the class instead, grab the id and then use a switch statement.
$('.itemDisabled').on('click', function () {
var id = this.id;
switch(id) {
case 'mmSaveForm':
// code
break;
case 'mmSaveAs':
// code
break;
case 'mmSaveExit':
// code
break;
}
});
Try to use .is(selector) to identify the element which has been clicked,
$('a.noTxtSelect1').click(function(e){
e.preventDefault();
if($(this).is("#mmSaveForm")){
} else if($(this).is("#mmSaveAs")) {
} else if($(this).is("#mmSaveExit")) {
}
});
If your links have id attributes all starting with 'mm' you could use:
$('a[id^=mm]').on('click', function(){
console.log(this.id);
});
Or on one or more classes:
$('a.itemDisabled').on('click', function(){
-or-
$('a.itemDisabled.noTxtSelect1').on('click', function(){
In the click event, you can use switch to determine the link clicked, which you can fetch using this or $(this)
e.g.:
Demo Fiddle
$('a[id^=mm]').on('click', function () {
switch (this.id) {
case "mmSaveForm":
alert(this.id);
break;
case "mmSaveAs":
alert(this.id);
break;
case "mmSaveExit":
alert(this.id);
break;
}
});
You can use the [attr^="value"] ["starts with"] selector:
$('[id^="mmSave"]').click(function(event){
event.preventDefault();
var action = this.id;
// do your business
});
You're thinking about this the wrong way. In your
$(document).ready(function() {})
you register for click events. So something like
$(document).ready(function() {
$("#mmSaveForm").click(function() {
// handle the click
});
});
may be you can try this
$(function(){
$('.linkclass').click(function(){
var link_text = $(this).text();
alert('the clicked link text is '+ link_text);
});
});
Use common class like a itemDisabled for click event and get id ,
$(".itemDisabled").click(function (e) {
e.preventDefault();
var id = this.id;
if (id === "mmSaveForm") {
} else if (id === "mmSaveExit") {
} else {}
});
No need jquery please look this code
<!DOCTYPE html >
<html >
<head>
<script>
function clickbtn(t)
{
alert(t.id);
/*if(t.id==...)
{
dosomething();
}
else
{
dootherthing();
}
*/
}
</script>
</head>
<ul>
<li>Save</li>
<li>Save As</li>
<li>Save And Exit</li>
</ul>
<body>
</body>
</html>
It work ok .
Hope this help!
This is my html page (Django template):
<div class="col">
{% for blog in blogs %}
<div class="post">
<h3>{{ blog.title }}</h3>
<div class="date">
<p>Created: {{blog.date_created|date:'d M Y'}}</p>
</div>
<p>{{ blog.brief|safe }}</p>
<ul class="nav justify-content-end">
<li class="nav-item">
<a class="nav-link active" href="{% url 'blog:edit' pk=blog.pk %}">Edit</a>
</li>
<li class="nav-item">
<a class="nav-link" id="publish" href="{{blog.pk}}">Publish</a>
</li>
<li class="nav-item">
<a class="btn btn-danger" id="remove" href="{{blog.pk}}">Remove</a>
</li>
</ul>
<br>
</div>
{% endfor %}
</div>
In my javascript file, this is what have and it works.
$(document).ready(function() {
console.log("document is ready!!!")
$('#id_bloglist').on("click", 'a#publish,a#remove', function(e) {
e.preventDefault()
var pk = $(this).attr("href")
if ($(this)[0].id == 'remove'){
console.log("remove link clicked, calling deleteBlog with pk = " + pk)
}
else if ($(this)[0].id == 'publish'){
console.log("publish link clicked, calling publishBlog with pk = " + pk)
}
return false;
});
});

Jquery click function trigger load more button

below i have 3 links as an tabs:
<li data-tab-id="self" class="tab selected">Near You<span class="unread-count hidden" style="display: none;"></span></li>
<li data-tab-id="friends" class="tab">Following<span class="unread-count hidden" style="display: none;"></span></li>
<li data-tab-id="user" class="tab">Your Activity<span class="unread-count hidden" style="display: none;"></span></li>
when i click the above link Jquery click function are triggered
$(".hd-ui-activity li a").click(function(e) {
e.preventDefault();
var tabid = $(this).parent().attr('data-tab-id');
if(tabid == "self"){
getFunc1(totalRecords);
} else if(tabid == "friends") {
getFunc2(totalFriendsRecords);
} else if(tabid == "user") {
getFunc3(totalUserRecords);
}
});
When each of the links/tabs are clicked the function eg getFunc1() are called which append an html to the following div (Each func have its own div)
<li data-section-id="following" data-component-bound="true">
<ul class="module-list">
<!-- USER ACTIVITY JSON -->
</ul>
<a class="ybtn ybtn-primary ybtn-large more-wishlist" href="#" onclick="javascript:getRecentActivityFriends(event)">
<span data-component-bound="true" class="loading-msg following">See more recent activity</span>
</a>
</li>
Only 4 list results are displayed on the div, when user click see more activity button, more result are loaded into div. The problems now is when the page load it display correctly 4 results but when i click the link again rather than a button all the data are displayed.Its difficult for me to navigate between tabs. How can i avoid this?
Update:
var totalFriendsRecords = '<?=$this->followingTotal?>';
function getRecentActivityFriends(event)
{
if (event != null){
disabledEventPreventDefault(event);
}
getFriendsActivity(totalFriendsRecords);
}
home.js
var totalFriendsRecordsView = 0;
function getFriendsActivity(totalFriendsRecords)
{
var activityHtml = ''
$.ajax({
url:baseUrl + "activity/feedfollowing",
data:{'total':totalFriendsRecordsView},
dataType:"json",
type:"POST",
success:function(data){
for(var i=0; i<data.length; i++){
activityHtml = '<p>'+data[i][name]+'</p>';
}
$('#activity-feed li[data-section-id=following] .module-list').append(activityHtml);
if( totalFriendsRecords <= totalFriendsRecordsView){
$('.following').text('Nothing beyond here ...');
$('.following').removeAttr('onclick');
$('.following').removeAttr('href');
}
}
});
}

Categories