Sajjad Sajjad - 1 month ago 5
HTML Question

How to use same JQuery method for elements having different Ids?

HTML FILE IS:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script src="myjquery.js"></script>
</head>
<a id='mylink1' href='#'>Click to Display First div</a> <br>
<div id='mydv1' style='display: none;' > I am First div</div>

<a id='mylink2' href='#'>Click to Display Second div</a> <br>
<div id='mydv2' style='display: none;' > I am Second div</div>
</body>




myjquery.js file is:

$(document).ready(function(){

$('[id^=mylink]').click(function(){
$('[id^=mydv]').show();
return false;
});
});


Actually I dont want to write two separate Jquery methods
$('#mylink1').click(function()
and
$('#mylink2').click(function()


But using the single Jquery method like above i.e.
$('[id^=mylink]').click(function()
causes to display both divs, even by clicking on only one hyperlink.

What correction is needed in above Jquery method so that clicking on a hyperlink displays only corresponding div.

Answer

Html code

<input type='button' id='mylink1'/>
<div id='mydv1' style='display:none'>
I am first div
</div>
<input type='button' id='mylink2'/>
<div id='mydv2' style='display:none'>
I am second div
</div>

Jquery Code

$('[id^=mylink]').click(function(event){
     var str=event.target.id;
     var Id='#mydv'+str.slice(str.indexOf('vish'),str.length)
     $(Id).show();
     return false;
     });

Fiddle Ex here

Comments