brainydexter
brainydexter

Reputation: 20386

How can I attach a click handler for multiple IDs and identify the ID within the handler in jQuery?

I'm very new to jquery and what would be a simple way to do this:

My server side code spits out html like this:

<div name="destinationName" id="1">NEW DELHI</div>  
<div name="destinationName" id="2">JAIPUR</div>

<div name="destinationContent" id="1" style=";">NEW DELHI details</div>
<div name="destinationContent" id="2" style="display:none;">JAIPUR details</div>

By default New Delhi details needs to be shown. When I click on Jaipur, I'd like to display Jaipur details instead. When I click on New Delhi again, I need to only display New Delhi details. The behavior is similar to jquery tabs.

Javascript:

<script type="text/javascript">
$(document).ready(function() {
    $('div[name="destinationName"]').click(function(){
        $('div[name="destinationContent"]:visible').hide();
        $('div[name="destinationContent"][id=this.id]').show();
       });
});
</script>

JSFiddle

When I click on Jaipur, both New Delhi and Jaipur are rendered. When I debugged through the code,

$('div[name="destinationContent"][id=this.id]').show();

this.id is what is causing the problem.

How can I refer this.id in the above script ??

PS: If I replace this.id with "2", it works fine. In the console, when I output `this'id', it returns "2". So, I'm not sure how to resolve this.


Also, can someone recommend me a good way to group similar divs (I'm using names to group similar divs and ids to identify an element within that group) ?

Upvotes: 1

Views: 154

Answers (4)

andyb
andyb

Reputation: 43823

Firstly the id is a unique identifier and by having multiple elements with the same ID can cause undesired behaviour in jQuery. Secondly, id cannot (validly) start with a number unless your page has the HTML5 doctype.

So onto the problem you are having...

To use the element id in the selector you need to access it outside of your selector string and concatenate the result with the rest of the selector, otherwise it's just part of the string. The error you are seeing is correct that JavaScript doesn't know what this.id is, so the following change should correct the error:

$('div[name="destinationContent"][id=' + this.id + ']').show();

However, this does not correct the duplicate id problem. It would be better to use a unique class attribute for each pair to link the <div>s together.

You can also take advantage of the class attribute on the destinationContent instead of the custom name so that your jQuery selectors are easier to write (class selectors can be accessed using the (dot) .), for example in this jsFiddle

If the details are always in the same order as the titles then you can use the index of the element to simply select the same destinationContent as the title, for example:

Edit: Updated code with alternate solution not relying on element index.

HTML

<h3 class="delhi">NEW DELHI</h3>
<h3 class="jaipur" >JAIPUR</h3>
<hr/>
<div class="destinationContent">
    <div class="delhi">NEW DELHI details</div>
    <div class="jaipur">JAIPUR details</div>
</div>​​​​​​​​​​​​​​​​​​

JavaScript

$(function() {
    var contents = $('.destinationContent div');
    contents.hide();

    $('h3').on('click', function(){
        contents.hide();
        $('.destinationContent div.' + this.className).show();
    });
});​

Upvotes: 2

user1432124
user1432124

Reputation:

Never repeat id and therefore i have not used any attribute and made this

<script type="text/javascript">
$(document).ready(function() {
    $('div[name="destinationName"]').click(function(){
$('div[name="destinationContent"]').hide();        
$('div[name="destinationContent"]:contains('+this.innerHTML+')').show();

       });
});
</script>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

You can't repeat ID's in a page and ID's should not be numeric in html4

Am changing the ID in first set of DIV's to a data- attribute, also changing name to class

<div class="destinationName" data-id="1">NEW DELHI</div>  
<div class="destinationName" data-id="2">JAIPUR</div>

JS

$('.destinationName').click(function(){
     /* change other "name" attributes to class */
     $('.destinationContent').hide();  
     var id= $(this).data('id');
     $('#'+id).show();
 })

Upvotes: 1

U.P
U.P

Reputation: 7442

First of all, Numeric Id's isn't a good idea.

Secondly, Give your divs Id's in the following format: MyDiv-1 MyDiv-2 and so on

Then, user

$("[id^='MyDiv']").click(function(){ ... });

This will hook event on all the divs that have Ids starting from MyDiv

Finally, in the click function

var id = $(this).attr("id").split("-")[1];

This will give you numeric id in variable id. You can use that to decide which div to show and which div to hide

You can further automate by giving your contect similar ids such as 'MyContent-1' and so on

Then you can simply append the id to "MyContent" and call show()

$("[id^='MyContent']").hide()
$("#MyContent-"+id).show()

Upvotes: 1

Related Questions