views:

52

answers:

2

Hello,

I have a form that is being generated on the fly in PHP using the below ($theFeatures is a multidimensional array):

<?php 
foreach($theFeatures as $theKey => $theValues) {
?>
    <input type="text" value="<?php echo $theValues['Key']; ?>" name="theFeatures[<?php echo $theKey; ?>]['Key']" size="6" />
    <input type="text" value="<?php echo $theValues['Value']; ?>" name="theFeatures[<?php echo $theKey; ?>]['Value']" /> <br />
<?php
}
?>

This should create two input boxes that look like this:

<input value="Type" name="theFeatures[4]['Key']" size="6" type="text" />
<input value="Bird Table" name="theFeatures[4]['Value']" type="text" />

How can I get the first part of the array ( [4] in the above example ) in jQuery so I can store that as a JavaScript variable and use it else where in my jQuery??

Cheers,

Andy

+3  A: 

You could try just storing the value in a separate attribute on the input and then retrieving that attribute with jQuery.

Adding the new attribute to the input

<input type="text" value="<?php echo $theValues['Key']; ?>" name="theFeatures[<?php echo $theKey; ?>]['Key']" size="6" key="<?php echo $theKey; ?>"/>

Retrieving the attribute with jQuery

var key = $("input").attr("key");
T B
This is probably the easiest way and you avoid having to parse a string.
Peter
Or you can also use the rel="" attribute.
Darryl Hein
Thank-you kindly. This is a genius solution!
Andy Barlow
+1  A: 

Certainly T B's suggestion could work. You can also do the following to get all input boxes that have "Key" in the name and get the value in the first set of square brackets. This will get any input object with the name containing Key.

$("input[name*=Key]").each(function() {
    var name = $(this).attr("name");
    var key = name.substring(name.indexOf("[") + 1, name.indexOf("]");
    //do whatever is needed with key
 });
justkt