2013-03-09 63 views
2

我在html中有一個表單,並且我想使用javascript從字段中提取最高數字。例如:從表單域獲取最高數字

 

<input id="temp_0__Amount" name="temp[0].Amount" type="text" value="lorum ipsum"> 
<input id="temp_1__Amount" name="temp[1].Amount" type="text" value="lorum ipsum"> 
<input id="temp_2__Amount" name="temp[2].Amount" type="text" value="lorum ipsum"> 
 

在這種情況下,我想一個javascript產生2

我試圖用jQuery的東西,但我不能進一步得到那麼:

$('input[name^="temp"]').last().name; 

這將產生temp[2].Amount。但我只想提取2.不是整個句子。而且我知道我可以使用子串等東西,但我想知道是否有「乾淨」的方式。

+3

在我看來, 「乾淨」 的方式是添加一個'data-'屬性只包含你的代碼需要的字符串。 – Pointy 2013-03-09 16:20:35

+1

@Pointy - 有完全相同的想法。 – j08691 2013-03-09 16:20:56

+0

@有點抱歉,但這是不可能的,這些字段是由ASP.NET MVC生成的。我想檢索最後一個數字,以便可以在下一個數字中添加另一個輸入字段。 – SynerCoder 2013-03-09 16:22:05

回答

4
var max = Math.max.apply(Math, $('input').map(function(){ 
     return this.name.match(/\d+/); 
}).get()); 

console.log(max); 

http://jsfiddle.net/fmpw3/

+0

Thx,它工作。我會在5分鐘內接受。 – SynerCoder 2013-03-09 16:28:01

0

如果你想只提取數2:

$('input[name^="temp"]').size()-1; 
0

這裏使用數據 - 屬性 -

<input id="temp_0__Amount" name="temp[0].Amount" data-amount="0" type="text" value="lorum ipsum"> 
<input id="temp_1__Amount" name="temp[1].Amount" data-amount="1" type="text" value="lorum ipsum"> 
<input id="temp_2__Amount" name="temp[2].Amount" data-amount="2" type="text" value="lorum ipsum"> 

,你可以在jQuery中獲取值: -

var amount = $('input[name^="temp"]').last().data('amount'); 

見現場演示 Live demo link

0

小花哨(多了一個解決方案):

var max = $('input').map(function(){ 
    return this.name.match(/\d+/); 
}).get().sort().reverse()[0]; 

http://jsfiddle.net/wSmEV/

0

嘗試:

var lastName = $('input[name^="temp"]').find(":last").prop("name"), 
    amount = lastName.replace(/^temp\[|\]\.Amount/g,'');