I have a set of dynamically generated anchor tags in a for loop as follows:
<div id = "solTitle"> <a href = "#" id = "' + tagId + '" onClick = "openSolution();"> ' + solTitle + '</a></div> <br>';
Once this code is executed the html output for one of the case would look like:
<div id = "solTitle"> <a href = "#" id = "solution0" onClick = "openSolution();">Solution0 </a></div> <br>
<div id = "solTitle"> <a href = "#" id = "solution1" onClick = "openSolution();">Solution1 </a></div> <br>
Now I want different texts to be displayed on clicking the above links.
openSolution() looks like this:
function openSolution() {
alert('here');
$('#solTitle a').click(function(evt) {
evt.preventDefault();
alert('here in');
var divId = 'summary' + $(this).attr('id');
document.getElementById(divId).className = '';
});
}
When I execute it and click on either of the links, the flow doesnot come inside the jquery click handler. I checked it by the above alerts used. It only displays the alert – ‘here’ and not the alert – ‘here in’.
On clicking the link second time, everything works perfectly with correct value of divId.
The first time you click the link, the
openSolutionfunction is executed. That function binds theclickevent handler to the link, but it won’t execute it. The second time you click the link, theclickevent handler will be executed.What you are doing seems to kind of defeat the point of using jQuery in the first place. Why not just bind the click event to the elements in the first place:
This way you don’t need
onClickattributes on your elements.It also looks like you have multiple elements with the same
idvalue (“solTitle”), which is invalid. You would need to find some other common characteristic (classis usually a good option). If you change all occurrences ofid="solTitle"toclass="solTitle", you can then use a class selector:Since duplicate
idvalues is invalid, the code will not work as expected when facing multiple copies of the sameid. What tends to happen is that the first occurrence of the element with thatidis used, and all others are ignored.