How to get which link has been clicked in jquery - javascript

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;
});
});

Related

Execute JS function from Code behind (with Parameter)

I'm working on some Code which loads the a page and selects the required nav tab. This works great in the .aspx file, but I don't know how to trigger with the code behind.
Here is the element that I would like to select
<li class="nav-item" runat="server">
<a class="nav-link" id="pills-request-tab" data-toggle="pill" href="#pills-request" role="tab" aria-controls="pills-request" aria-selected="false" onclick="OnTabChange(this)">Request</a>
</li>
JS code
$(document).ready(function () {
debugger;
var tabName = $("#TabName").val() != "" ? $("#TabName").val() : "pills-home";
$('.tab-content div').removeClass('active').removeClass('show');
$('#' + tabName + '-tab').addClass('active');
$('#' + tabName).addClass(' show active');
if ($("#TabName").val() != "" && $("#TabName").val() != "1") {
("#pills-user-tab").addClass(' admin');
("#pills-holiday-tab").addClass(' admin');
("#pills-add-tab").addClass(' admin');
}
});
function OnTabChange(currentTab) {
if (currentTab != null)
console.log(currentTab);
$("#TabName").val(currentTab.id.replace('-tab', ''));
}
Code behind
Page.ClientScript.RegisterStartupScript(this.GetType(), "pills-request-tab", OnTabChange(this), true);
I know that the parameter in Code behind is not OnTabChange(this). I would like to know how I can pass the object from code behind.
You simply call the OnTabChange like this. Only this will not work. You will need to pass a string.
Page.ClientScript.RegisterStartupScript(this.GetType(), "pills-request-tab", "OnTabChange('tabID')", true);
The Solution look like this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "pills-request-tab", "OnTabChange(<a class='nav-link' id='pills-request-tab' data-toggle='pill' href ='#pills-request' role ='tab' aria-controls='pills-request' aria-selected='false' onclick ='OnTabChange(this)' > Request</a>)", true);

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

bind multiple id using on()

<a id="abc">First</a>
<a id="xyz">Second</a>
$('body').on('click','#a,#b',function(){
btn = $(this).attr('id');
if(btn == "abc"){ //do something };
});
Why my above code worked when I click abc id but not the later button? Did I bind it wrongly?
Your selectors are not correct and do not match your IDs:
$('body').on('click','#abc,#xyz',function(){
var btn = $(this).attr('id');
alert(btn);
if(btn === "abc") {
// Do something
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="abc">First</a>
<a id="xyz">Second</a>

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

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.

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