click events issue in jquery.

Posted by alex on Stack Overflow See other posts from Stack Overflow or by alex
Published on 2011-01-03T01:09:58Z Indexed on 2011/01/03 1:53 UTC
Read the original article Hit count: 638

Filed under:
|
|
|
|

I don't know if the title explain this situation well. Below is a code i wrote to create div elements when the button is pressed. Then By clicking on any of the created divs, we can change the div background by choosing a color from the drop down box. However if i click on another div and tried to change the color by selecting another color from the drop down, the previously clicked divs also gets affected by the new color. Why is this happening. I only want the selected div to change color, without affecting the previously clicked divs. I read allot of threads on this site, some of which talks about unbinding clicks, but I'm unable to solve the problem. Thanks for the help.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<style> 
.aaa { width:100px; height:100px;background-color:#ccc;margin-bottom:5px;}
p{widht:500px; height:500px; margin:0px; padding:0px;border:2px solid red;color:#000;}
</style>

<select id="item_select" name="item"> 
    <option value="1">red</option> 
    <option value="2">blue</option> 
    <option value="3">green</option> 
</select>

<button>Click to create divs</button>
<p id="ptest"></p>


<script type="text/javascript">
var dividcount = 1;
$("button").click(run);
function run(){
 var myDiv = $('<div id=lar'+dividcount+' class=aaa></div>');
 $(myDiv).clone().appendTo('#ptest');
 $(dividcount++);
 $("div").bind('click',(function() {
  var box = $("div").index(this);
  var idd = (this.id);
  $("#"+idd).text("div #"+idd);
  $("select").change(function(){
   var str= $("select option:selected").text();
   $("#"+idd).css("background-color",str);
  });
 }));
}; 
</script>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about colors