Friday, August 31, 2012

Index PHP Array to use in Javascript / Javascript array

So here is what I wanted, I wanted to the text of check box when clicked on check box like
<input type='checkbox' value='1' name='chkbox'>First chk box</input>

So I wanted 'First chk box' when clicked on it, in here you might be able to simply get it using innerHTML but my case was bit different so I got a php array that had id=>value (1=>'First chk box') array now the issue is you can't use it in javascript

So step 2 is converting php array to javascript array, following are the things you can do

1. Simply make a javascript array and put php values in it
var jsArray = new Array('<?=$phpArr[0]?>',<?=$phpArr[1]?>',....);

That doesn't work in my case because my indexes were different

2. You can have insertion in JS Array using the splice function to insert in mid, you can google that, but the issue with that is you can't have a javascript array like

arr[1] = index1
arr[2] = index2
arr[5] = index5

means you need EACH index defined which is not my case, I could have skipping index so here is solution for me, or you if you have similar issue... or any of above might work for you...

3. var jsArray = <?php echo json_encode($phpArray) ?>;
Now if could do is simply using
jsArray[chkbox.value] 
and it would give me 'First chk box'

No comments:

Post a Comment