0

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

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

2 Comments

This is probably the easiest way and you avoid having to parse a string.
Or you can also use the rel="" attribute.
1

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
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.