<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>
Related
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
I have spent hours trying to resolve this problem and reviewing other similar StackOverflow questions (1) (2), but none seem to have an answer to my problem..
I can't get past this error: ReferenceError: id is not defined. Alert does not show too.
$("button.btn-tag-cat").click(function(e){
e.preventDefault();
var id = $(this).prop('id');
alert(id);
id.find('span').show();
}, function(){
id.find('span').hide();
});
I have tried the following ways to using the id variable but none work.
$(id).find('span').show();
$("#" + id).find('span').show();
However, when i remove the chunk of code below the alert, the alert pops up with the correct id belonging to the button.
$("button.btn-tag-cat").click(function(e){
e.preventDefault();
var id = $(this).prop('id');
alert(id);
});
View partial:
Button id references a ruby local variable id="<%= name %>"
<% q.categories_name_in.each do |name| %>
<button type="button" class="btn btn-outline-primary btn-lg btn-tag-cat" id="<%= name %>"><%= name %><span class='glyphicon glyphicon-remove'></span></button>
<% end %>
As you've noted, the error is chaining functions in the click listener.
In order to get the id attribute, you can use the jQuery attr function, like:
$("button.btn-tag-cat").click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
alert(id);
$('#' + id).find('span').show();
});
$("button.btn-tag-cat").click(function(e) {
e.preventDefault();
var id = $(this).attr('id');
alert(id);
$('#' + id).find('span').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn-tag-cat" id="hallo">Press</button>
Here, in your code I will beautify it to see your mistake:
$("button.btn-tag-cat").click(
function(e) {
e.preventDefault();
var id = $(this).prop('id');
alert(id);
id.find('span').show();
},
function() {
id.find('span').hide();
}
);
notice the second function has
function() {
id.find('span').hide(); // right here
}
but the id is not defined yet
try
function() {
var id = $(this).prop('id'); // this first
id.find('span').hide();
}
Have a dynamic html div
<a data-id="17" onclick="getcustomer();">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
On the above anchor's on click.it calls this function
function getcustomer(){
var id = $(this).data('id');
alert (id);
$.post(base_url+'who/customer', {
customer_id: id
}, function(data, status){
console.log(data);
});
}
But alert receiving is undefined.
How will I take data-id value?
This is dynamic field. This a's are added after dom load.
this does not refer to the element but to window
Pass this as argument for getcustomer function
function getcustomer(elem) {
var id = $(elem).data('id');
alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" onclick="getcustomer(this);">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
Or better use jQuery event binding using .on method
$('.eventBinding').on('click', function() {
var id = $(this).data('id');
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" class='eventBinding'>
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
Pass the object to the method,
<a data-id="17" onclick="getcustomer(this);">
Then the code will be,
function getcustomer(obj) {
var id = $(obj).data('id');
alert(id);
$.post(base_url + 'who/customer', {
customer_id: id
},
function(data, status) {
console.log(data);
});
}
Try this:
<a data-id="17" onclick="getcustomer(this);">
function getcustomer(curr_obj){
var id = $(curr_obj).data('id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}
What if you use $(this).attr('data-id');
Try this as well, if it works. Its just simple one line of code.
$('a').on('click', function(){
var id = $(this).attr("data-id");
alert(id);
});
Or you can try this as well, according to your code,
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}
Use this script
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}
I want to retrieve the ID of the clicked element (on the 'onclick; event.
<script>
function myFunction(element)
{
var $id = element.id;
$($id).click(function() {
$.get('ajaxTestSrvlt?test=1', function(responseText) {
$('#firstName').val(responseText); with the response text.
});
});
};
</script>
This is the element this function was called upon. I would like to get the ID of this raw from the above script. This only works when I directly give the "clickableRow" as to id to the Script. The "ID" is to be changed dynamically
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal" onclick="myFunction(this)">
There is no need to have a inline event handler
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal">
then
jQuery(function () {
$('.clickable-row').click(function () {
var $this = $(this),
id = this.id;
$.get('ajaxTestSrvlt?test=1', function (responseText) {
$('#firstName').val(responseText);
//here `id` is the id of the clicked tr
});
});
})
Try this
function myFunction(ele)
{
var id=$(ele).attr("id");
$('#'+id).click(function() {
//code here
});
}
Simply use this
onclick="myFunction(this.id)
Instead of
onclick="myFunction(this)
Get your id on my function
function myFunction(getid) {
alert(getid);
}
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;
});
});