Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - adding elements into an array

I'm trying to add the ID's, which are the $hexcode values from the html span into an array. How do I do this with jQuery? Eventually, I'm going to need to grab these hexcode values and match them to a color index.

<?php
// display every color in the world

$r = 0;
$g = 0;
$b = 0;
$i = 0;
$step = 16;

for($b = 0; $b < 255; $b+=$step ) {
    for($g = 0; $g < 255; $g+=$step) {
        for($r = 0; $r < 255; $r+=$step) {
        $hexcolor = str_pad(dechex($r), 2, "0", STR_PAD_LEFT).str_pad(dechex($g), 2, "0", STR_PAD_LEFT).str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
        echo '<span class="color_cell" id="'.$hexcolor.'" style="width: 5px; height: 5px; background-color:#'.$hexcolor.'; border: 1px dotted;">&nbsp;</span>'

        if($i%256 == 0) {
            echo "<br />";
        }
        $i++;
        }
    }

}
?> 
<script src="jquery-1.6.2.js"></script>
<script type="text/javascript">

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');
        //how do i add the ID (which is the $hexcolor into this array ids[]?
        ids.push($(this).attr('id'));       
    });
});

Thanks in advance!

like image 746
Richard Avatar asked Aug 09 '11 04:08

Richard


People also ask

How do you add an element to an array in array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.

How do you add an element to an array of elements?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array.

How do you append an array in JQ?

A better solution would be: var elements = []; for(x = 0; x < 1000; x++) { var element = $('<div>'+x+'</div>'); elements. push(element); } $('body'). append(elements);


2 Answers

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});
like image 57
ShankarSangoli Avatar answered Oct 12 '22 13:10

ShankarSangoli


var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});
like image 39
Brook Avatar answered Oct 12 '22 13:10

Brook