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>
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) ?
Firstly the
idis a unique identifier and by having multiple elements with the same ID can cause undesired behaviour in jQuery. Secondly,idcannot (validly) start with a number unless your page has the HTML5 doctype.So onto the problem you are having…
To use the element
idin 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 whatthis.idis, so the following change should correct the error:However, this does not correct the duplicate
idproblem. 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 jsFiddleIf 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
JavaScript