【问题标题】:Select Form Array Value Using JQuery使用 JQuery 选择表单数组值
【发布时间】:2010-01-15 16:58:02
【问题描述】:

我有一个使用下面的 PHP 动态生成的表单($theFeatures 是一个多维数组):

<?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
}
?>

这应该会创建两个如下所示的输入框:

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

如何在 jQuery 中获取数组的第一部分(上例中为 [4]),以便将其存储为 JavaScript 变量并在 jQuery 的其他位置使用它??

干杯,

安迪

【问题讨论】:

    标签: php javascript jquery


    【解决方案1】:

    您可以尝试将值存储在输入的单独属性中,然后使用 jQuery 检索该属性。

    将新属性添加到输入中

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

    使用 jQuery 检索属性

    var key = $("input").attr("key");
    

    【讨论】:

    • 这可能是最简单的方法,您可以避免解析字符串。
    • 或者你也可以使用 rel="" 属性。
    • 非常感谢。这是一个天才的解决方案!
    【解决方案2】:

    T B 的建议当然可行。您还可以执行以下操作来获取名称中包含“Key”的所有输入框,并获取第一组方括号中的值。这将获得名称包含 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
     });
    

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2014-04-20
      相关资源
      最近更新 更多