I’m trying to add elements into an Associative Array, which is colors = []
I want it to have the ["id":selected_color] but my browser keeps crashing (an infinite loop somewhere?)
I’m not sure if I’m adding the elements into the array correctly.
What is happening is that I’m clicking on a span element, which has its ID value set to a hexcode value, and I’m trying to capture that value and associate it with the selected._color
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
var selected_color = "";
var colors = [];
$(document).ready(function() {
$(".color_cell").click(function(){
// ADD MY COLOR TO SELECTED COLOR'S ASSOCIATIVE ARRAY
colors[$(this).attr("id")] = selected_color;
console.log($(this).attr("id"));
$(this).css({'background-color':'white'});
$(this).unbind('click');
updateDisplay(colors);
alert("hi");
});
$(".btnColor").click(function(){
// MAKE SELECTED COLOR BE ME
alert("hey");
selected_color = $(this).attr("id");
}); // end button handler
}); // end ready()
function updateDisplay(colors) {
jQuery.each(colors, function(key, value) {
//it seems to crash here...
$("#storage_display").html("var "+$("#storage_display").html()+" " +value);
});
};
</script>
You’re defining colors as an array instead of an object.
You just need to initialize it properly:
Additional suggestion… there’s really no need for the jQuery.each here. Iterating over an associative array like this (let’s not argue the semantics of whether you can actually call this an associative array) looks like this: