Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
78
rated 0 times [  81] [ 3]  / answers: 1 / hits: 29639  / 10 Years ago, sat, may 24, 2014, 12:00:00

I have got a lot of span tags inside my div elements. Each div has a unique id.I want to add an onclick event to the span elements in each div uniquley. How can i do that?



  <div class=bootstrap-tagsinputid=1>
<span class=tag label label-info>Access control lists</span>
<span class=tag label label-info>Network firewall</span>
</div>


<div class=bootstrap-tagsinputid=2>
<span class=tag label label-info>Access control lists</span>
<span class=tag label label-info>Network firewall</span>
</div>


My current script which catches all the span elements irrespective of the div.



      $('span.label-info').click(function() {

var news=$('input[type=text][id=vuln<?php echo $model->v_id;?>]').val()+','+$(this).text();
$('input[type=text][id=vuln<?php echo $model->v_id;?>]').val(news);
return false;
});


How can i catch click on span elements inside each div separately?


More From » php

 Answers
50

I think you're looking at it the wrong way. Instead of having a separate click handler for each div, you can keep the shared click handler, but find out which div is the parent, and use its ID in the subsequent selectors.



$('span.label-info').click(function() {

// find the parent/ansector that is a div and has the class
var divId = $(this).closest('div.bootstrap-tagsinput').prop('id');

var news=$('input[type=text][id=vuln' + divId + ']').val()+','+$(this).text();
$('input[type=text][id=vuln' + divId + ']').val(news);
return false;
});

[#70862] Thursday, May 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devlin

Total Points: 474
Total Questions: 113
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;