2016-07-23 22 views
0

我想將所有輸入類型的數字格式化爲逗號分隔值,我找到了通過網絡進行轉換的代碼,但它不是以我想要的方式工作,它應該將所有輸入數字轉換成特定的格式。在頁面加載時用逗號格式化的數字型號

我也嘗試過,做類型文本,但它仍然不會工作。

$(document).ready(function() { 
 
    $(".number").each(function() { 
 
    var _val = $(this).val(); 
 
    $(this).val(_val.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input name="locationError" class="number" type="text" value="1221312321" readonly/> 
 
<input name="locationError" type="text" value="1221312321" class="number" readonly/>

這是不同的,因爲我希望它在文檔上載

+1

變化爲type =文本 – charlietfl

+0

我試過,但它WOT工作 – SCS

+0

工作正常這裏https://jsfiddle.net/tvkswd75/ – charlietfl

回答

1

變化type="number"type="text"或HTML中TYPE = 「貨幣」。

另外請記住,要將jquery選擇器更改爲$("input[type='text']")$("input[type='currency']"),以便在您的特定片段場景中工作!

$(document).ready(function() { 
 
    $("input[type='text']").each(function() { 
 
    var x = $(this).val(); 
 
    alert(x); 
 
    $(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input name="locationError" type="text" value="1221312321" /> 
 
<input name="locationError" type="text" value="1221312321" />

+1

也許我沒有在jsfindle中測試代碼時包含jquery ..但是謝謝 – SCS

+1

增加了一個班級號碼而不是文本來擁有獨特的 – SCS

+0

好得多。我只是從你的代碼片段中複製並且編輯最少的,爲最小的改變的答案。 – Iceman