簡體   English   中英

計算標簽和文本框的百分比

[英]Calculating the percentage for label and textbox

我有幾個輸入字段,用戶可以在第一次訪問特定頁面時輸入值,這些值將保存到數據庫中,並且每次在文本框中輸入值時都會調用該函數,因為它將顯示這5個值占總數的百分比。

當用戶離開表單並返回時,將顯示標簽,而不是文本框。 下面的代碼對這樣的任務是正確的方向嗎?它將動態地選擇正確的參數“ .text”或“ .val”來專門獲取值,因為標簽將在用戶下次返回時填充? 我想自動執行此過程,而不是自己附加每個標簽值。

我已標記出我在哪里遇到麻煩

function calcABC(e) {

//Declare array of numeric selectors
var arr = ["a", "b", "c", "d", "e"];
var x = "";
var y = "";
if (e == "label") {
    x = "lbl_"
    y = ".text()";
}
else {
    x = "txt_"
    y = ".val()";
}

//HAVING TROUBLE HERE VVVVVVV
alert(eval("$('#' + x + arr[0]) + y)"));
alert("hello");

//loop through the array and get the value for that array index
var before = 0;
for (var i in arr)
{
    before += isNaN(parseInt($("#"+ x + arr[i]).val())) ? 0 : parseInt($("#" + arr[i]).val())
}

//Apply the total to the global variable
ABCTotal = before;

//Loop through the numbers and get the precentage value and append the value to the relevant area
for (var j in arr)
{
    console.log($("#" + x + arr[i]).val())
    var val = isNaN(parseInt($("#" + x + arr[j]).val())) ? 0 : parseInt($("#" + arr[j]).val());
    $("#txt" + arr[j] + "Prec > small").text(calcPrec(val).toFixed(2) + "%");
}

//Set the total field
$("#txt_ABCTotal").text(ABCTotal);
}
// Nice function to quickly calculate the precent value from a total
function calcPrec(val)
{
    return (val * 100) / ABCTotal;
}

我希望這是有道理的! 無論如何,請提供任何幫助!

為了避免使用eval(強烈建議使用eval),最好執行y ='text'或y ='val',然后使用數組表示法調用該函數,例如:

$('#' + x + arr[0])[y]()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM