Get the id of the clicked-upon div - javascript

I want to select the id of the current div when I click on it in jQuery.
For example, say I have HTML like this:
<div class="item" id="10">hello world</div>
<div class="item_10">hello people</div>
When I click on the first div on .item class, I want to copy the id of the current div + adding to it the number (10), so it will be ("div id" + 10) equal to the second dev class = item_10.
I tried to use currentid = this.id; but it doesnt work :( !

First, note that id attributes starting with numbers are syntactically illegal in HTML4. If you're using id="10" make sure that you're using the HTML5 doctype (<!DOCTYPE html>).
It's hard to say why what you were doing didn't work without seeing your actual code. Presumably it is because you were registering for the event on a higher element (like the body) and this.id was the id of that higher element and not the element you clicked on.
In this case, you want to use the target property of the event to find what you clicked on. For example:
$(document.body).click(function(evt){
var clicked = evt.target;
var currentID = clicked.id || "No ID!";
$(clicked).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/
If you were registering on the specific elements instead, then this.id does work:
$('div').click(function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/1/
This is sub-ideal, however, because:
It makes many event handler registrations instead of 1, and
If additional divs are added to the document after this code is run, they will not be processed.
Under jQuery 1.7, you use the .on method to create a single event handler on a parent element with selectors for the kinds of elements you want to catch the event on, and have this set to them. In code:
$(document.body).on('click','div',function(evt){
var currentID = this.id || "No ID!";
$(this).html(currentID);
})
Seen in action: http://jsfiddle.net/Gra2P/2/

I think you're trying to do something like:
$(".item").click(function(){
var id = $(this).attr("id");
var el = $(".item_" + id);
});
Now el is your second div.

You can simply use this.id
$('div').click(function() {
var divid = this.id;
alert($('.item_'+divid).html());
});
Demo

Something like this?:
$('div').click(function() {
theId = $(this).attr('id');
//Do whatever you want with theId.
});

This can be done as:
$('.item').click(function() {
var divId = $(this).attr("id");
});

Related

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Get DIV ID where Class is selected?

I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/

how to pass runtime parameters in jquery functions?

I m new to jquery. My requirement is to pass rowid(unique id of each record of a table) in a jquery function. I can get rowid only at runtime. so how can I bind click event to the tag whose id is this rowid.
Upd
Del
$(what to pass here).bind('click',function(ev) {
_operation(para1,para2); // function which is going to perfom action
ev.preventDefault();
return false;
});
get the id , and acording to id do what ever you want
$('a').on('click',function(){
var id = $(this).attr('id');
if(id == //what you want)
{
//function 1
}
else
{
//function 2
}
return false;
});
If there are any similarities between the IDs, you can use one of the attribute selectors such as:
ID contains
$('[id*="something"]')
ID begins with
$('[id^="something"]')
http://api.jquery.com/category/selectors/
A better approach would be to place all of the dynamically named anchors into a container, and then select on that:
<div id="container">
<a ...></a>
<a ...></a>
</div>
Then you would select all the child anchors:
$('#container > a').click(...);
It's hard to find a good selector from so few HTML code. Use a class on your markup if possible:
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Upd</a>
<a class="roww" href="javascript:void(0)" id="`string(rowid(Gatepass))`">Del</a>
then you can use $('.roww') to query your nodes.
Here's what you can do to get the id from the event handler:
function( ev ) {
//wrap the element with jQ:
var jel = $(this);
//Then access attributes with .attr() getter:
var id = jel.attr('id');
... //do whatever you want now.
... // there's a quicker alternative to get the id without jQuery, simply:
... // var id = this.id
}
if the id comes dynamically from the server, put inside the function the same id + hash for id selctor
$(what to pass here) => $("'#" + string(rowid(Gatepass)) + "'")

JS: Click one div, change another div value

I have a vote button I created that is contained within a .vote_div. 2 parts: .vote_num for the vote total, and .vote for the vote button. The page has a list of items so I need to make sure when the user clicks .vote, it changes the corresponding .vote_num + 1.
My JS function worked when the .vote actually was the total votes, but now I am seperating the two. How do I grab the right .vote_num on the .vote click?
Thanks!
<script>
$(".vote").click( function() {
var votes = $(this).attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
$(this).text(parseInt(votes) + 1);
return false;
});
</script>
<div class="vote_div">
<span class="vote_num" votes='{{host.num_votes}}'>{{host.num_votes}}</span>
<span class="vote" id="{{host.user.id}}">Vote</span>
</div>
EDIT & SOLUTION:
Got it working using $(this).parent() :
<script>
$(".vote").click( function() {
var votes = $(this).parent().find('.vote_num').attr('votes');
$.post(
'{% url vote %}', {
"id":this.id,
}, function(data) {});
this.className = "voted";
votes = parseInt(votes) + 1;
$(this).parent().find('.vote_num').text(votes);
return false;
});
</script>
try:
var votes = $(this).parent().find('.vote_num').attr('votes');
It goes to the parent of the clicked div then looks for an element with class vote_num then grabs the votes attributes.
#James answer should work, but this should give you a little more freedom to rearrange the two divs and add other elements so long as they share the parent.
To be even more robust you could do (note the 's' on "parents")
var votes = $(this).parents('.vote_div').find('.vote_num').attr('votes');
This will allow the elements to be nested arbitrarily deep as long as they only have a single parent with a class of `vote_div'.
See: http://api.jquery.com/parent/ , http://api.jquery.com/parents/ , and http://api.jquery.com/find/
if you have multiple class with vote, maybe you should use each()
$(".vote").each(function () {
var current = $(this);
current.click = function () {
// the rest of your function
}
})
Assuming I've understood the question correctly, and also assuming that your vote_num element is always the first element in the vote_div element:
var votes = $(this).siblings().eq(0).attr("votes");
Put this inside your click event handler will get the votes attribute from the first sibling element of the clicked element.
You can make this simpler if you are sure the element in question will always be directly before the clicked element:
var votes = $(this).prev().attr("votes");
var votes = $(this).attr('votes');
'votes' does not belong to class 'vote', it belongs to class 'vote_num'
so the line should be
var votes = $(".vote_num").attr('votes');
$('.vote').click(function(){
var $vote_num_obj = $(this).parent().find('.vote_num');
var new_vote_num = parseInt($vote_num_obj.attr('votes'))+1;
$vote_num_obj.attr('votes', new_vote_num);
$vote_num_obj.html(new_vote_num);
});
Put this script inside $('document').ready(function(){ ..here.. });
I suggest to change votes attribute of your span.vote_num to data-votes and change also the jquery attribute selector, this way it will be standard compliant.

How to get the id of an element on a button click in mootools(1.1)

I have a bunch of links with non-pre-determined id's like so:
Remove 123
Remove 234
Remove 567
Remove 890
I have an event handler like so:
$$('.remove_pid').addEvents({
'click': removePid
});
which calls this function
function removePid(event)
{
alert('yo what is my element id???');
}
So the question is how do i get the element id in the function removePid()?
UPDATE:
#Aishwar, event.target.id seems to work in the following case, but not specifically in my case
<img src="/123.jpg" id="pid_123">
UPDATE 2:
I thought it was inconsequential, but instead of the text "Remove 123" I actually have an image like so:
<img src="/123.jpg">
So, thanks for #Dimitra for pointing it out. I was surprised with the de-vote but am happy to say i probably deserve it.
I do not have experience working with mootools. But I would guess you can just do something along these lines, in removePid:
var element = event.srcElement || event.target
element.id // is the element's id, element is the DOM element itself
as per the markup posted in the FINAL update:
http://www.jsfiddle.net/dimitar/Sr8LC/
$$('.remove_pid').addEvents({
'click': function(e) {
new Event(e).stop();
var id = this.getProperty("id");
alert(id);
alert(id.replace("pid_", ""));
}
});
to use a named function and keep the event:
var removeProduct = function(e) {
new Event(e).stop();
var id = this.getProperty("id");
alert(id);
alert(id.replace("pid_", ""));
};
$$('a.remove_pid').each(function(el) {
el.addEvents({
'click': removeProduct.bind(el)
});
});
within both functions, this will refer to the trigger element (the anchor), so you can read it's property, etc. this.getFirst() will reference the image (if you want it).
Think I found it:
function removePid(event)
{
//alert('yo what is my element id???');
$(event.target).getParent('a').getProperty('id');
}
This works in FF 3.6

Categories