2013-02-19 76 views
0

我有一個<table>動態生成的行(<tr>’s)。jquery查找另一個號碼的下一個/最接近的多個號碼

在每一行中,我都有一個特定的單元格(<td>),其中顯示了一個文本框。在該文本框中,我添加了一個保存特定值的自定義data-roundingrule屬性(在每一行中,data-roundingrule屬性可能(或可能不)具有不同的值)。

這裏有什麼樣的文本框可能看起來像兩個例子:

<input type=」text」 id=」txt-1」 name=」txt-1」 data-roundingrule=」2」> 
<input type=」text」 id=」txt-2」 name=」txt-2」 data-roundingrule=」13」> 

我的目標是建立在每一個驗證,如果輸入值(用戶)是的倍數文本框更改事件存儲在data-roundingrule屬性中的值。

如果用戶輸入的值是data-roundingrule屬性的倍數,那麼太棒了!將東西保留原樣...

如果用戶輸入的值不是data-roundingrule屬性的倍數,則查找/獲取/獲取下一個最接近的數字,該數字將爲data-roundingrule屬性的倍數。

下面是一個例子:

考慮上述兩個文本框,文本框在1中,用戶輸入如果值1是數據roundingrule組的至2的倍數由於1.改變事件的值驗證事實並非如此,那麼我需要更改用戶輸入的值並將其設置爲2.

同樣,對於第二個文本框......假設用戶在文本框中輸入了值4,則4不是13,所以我需要將用戶的輸入從4更改爲13.

如果用戶在secon中輸入了值16 D文本框中,16不是13的倍數,所以我需要將用戶的輸入從16更改爲26(這是下一個倍數)。

希望這是有道理的...

真誠地提前致謝!

+0

到目前爲止,我有這調用另一個函數的變化情況。除了data-roundingrule屬性中的值之外,該其他函數還獲取該特定文本框的用戶輸入。有了這個,我可以計算出用戶的輸入是多重的,但是我沒有想到的是如何找到下一個/最近的倍數,以防用戶的輸入不是倍數。 – Vlince 2013-02-19 18:15:13

回答

0
$('input').change(function() { 
    var rr = parseInt($(this).data('roundingrule'), 10); 
    if ($(this).val() % rr != 0) $(this).val(Math.ceil($(this).val()/rr) * rr); 
}); 

jsFiddle example

2

你可以做這樣的事情:

$('input').change(function() { 
    var round  = parseInt($(this).attr('data-roundingrule'), 10); 
    var value  = parseInt($(this).val(), 10); 
    var remainder = value % round; 

    if(remainder != 0) { 
     $(this).val(value + round - remainder); 
    } 
}); 
0

添加一個onchange方法

<input type=」text」 id=」txt-2」 name=」txt-2」 data-roundingrule=」13」 onchange="roundUp(this)"> 

然後定義像這樣使用jQuery的功能...

function roundUp(el) 
{ 
    var num = $(this).attr("data-roundingrule"); 
    num = num * 1 // lazy coercion to numeric type 

    var val = $(this).attr(val); 

    val = val * 1; 
    if(val % num === 0) 
    { 
    //it's good 
    } 
    else 
    { 
    while(val % num !== 0) 
    { 
     val += 1; 
    } 
    } 
} 

你應該可能會添加一些錯誤檢查,雖然...