【问题标题】:How to select elements by name using RegEx如何使用 RegEx 按名称选择元素
【发布时间】:2016-03-05 15:19:13
【问题描述】:

我有一个包含一些记录的表,在每一行 tr 我有两个文本框在两个 TD, 所有文本框都没有IdClass,它们只有一个Name,它们的名称如下所示

PurchaseDetails[some number].Quantity
PurchaseDetails[some number].PurchasePrice

喜欢:

PurchaseDetails[1457160526936].Quantity
PurchaseDetails[1457160526936].PurchasePrice

我使用以下代码但不起作用:

var ProductQuantity = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].Quantity]").val();
var ProductPurchase = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].PurchasePrice]").val();

我的完整html代码是:

 <tr >                                                        
 <td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].Quantity" ></td>
 <td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].PurchasePrice" ></td>
 </tr>

【问题讨论】:

  • @Tushar 请查看更新。
  • 这不是完整代码。也许,创建现场演示。
  • 好的,对不起。等等。
  • @t 请看:[1]:jsfiddle.net/ufa4sLb7/5

标签: javascript jquery regex


【解决方案1】:

如果当前上下文中只有一个带有该前缀和后缀的元素($(this)),则可以使用attribute starts with selectorattribute ends with selector

$(this)
    .find('input[name^="PurchaseDetails"][name$="Quantity"]').val();

【讨论】:

【解决方案2】:

您可以使用 filter() 使用正则表达式进行过滤

// replace `$('input')` to `$(this).find('input')` to avoid searching in global context

var ProductQuantity = $("input").filter(function() {
  return /^PurchaseDetails\[\d+\]\.Quantity$/.test(this.name);
}).val();
var ProductPurchasePrice = $("input").filter(function() {
  return /^PurchaseDetails\[\d+\]\.PurchasePrice$/.test(this.name);
}).val();

console.log(ProductQuantity, ProductPurchasePrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="PurchaseDetails[1457160526936].Quantity" value=1 />
<input name="PurchaseDetails[1457160526936].PurchasePrice" value=2 />

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 2014-11-10
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2022-11-14
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多