2013-04-18 2 views
0

이 코드에서는 양식을 기반으로 여러 값을 추가하고 새 합계를 만드는 가장 낮은 값을 뺍니다. 코드는 훌륭하게 작동합니다. 제가하고 싶은 것은 바닥에 새 합계를 쓰는 것 대신에 3을 원합니다. 빼기가없는 원래 합계, 하나를 빼는 가장 낮은 가격의 값 그리고 마지막으로 실제 합계를 말합니다. 새로운 총. 지금은 새로운 합계 만 표시합니다.수학 함수 내부에서 특정 값을 어떻게 호출합니까?

예 : $ 5는 스카프, $ 10은 모자, $ 20은 모자입니다. $ 35에 해당하는 모든 값을 더하고 $ 5의 스카프 인 최저값을 뺀 다음 30 달러를 새로 얻습니다. 이것을 하단에 표시하고 싶습니다.

합계 : $ (35) 할인 : $ -5 새로운 합계 : $ (30)

기능은 이미 난 그냥 함수에서 호출하는 방법을 모른다, 모든 값을 파악한다.

// All selected prices are stored on a array 
var prices = []; 

// A function to remove a item from an array 
function remove(array, item) { 
    for (var i = 0, len = array.length; i < len; i++) { 
     if (array[i] == item) { 
      array.splice(i, 1); 
      return true; 
     } 
    } 
    return false; 
} 

function calculateSectedDues(checkbox, amount) { 
    // We add or remove the price as necesary 

if (checkbox.checked) { 
    prices.push(amount); 
} else { 
    remove(prices, amount); 
} 

// We sum all the prices 
var total = 0; 
for (var i = 0, len = prices.length; i < len; i++) 
    total += prices[i]; 

// We get the lower one 
var min = Math.min.apply(Math, prices); 


if(min == Infinity) { min = 0; }; 

// And substract it 
total -= min; 

document.grad_enroll_form.total.value = total; 

}

+0

사용자가 하나의 항목 만 선택하면 어떻게됩니까? 이 경우 disount 후의 총 가격은 0이됩니다 ... – cfs

+0

실제로는 제가하는 일과 실제로는 괜찮지 만 그게 누군가에게 어떻게 문제가 될지 알 수 있습니다. –

답변

1

여기에 단지가 값를 써 당신을 위해 몇 가지 기본적인 코드입니다. I 여전히은 배열에서 요소를 제거하는 루핑에 동의하지 않습니다. 이 같은

<span id="value"></span> 
var prices = []; 

function remove(arr,itm){ 
    var indx = arr.indexOf(itm); 
    if (indx !== -1){ 
     arr.splice(indx,1); 
    } 
} 

function calculateSectedDues(checkbox, amount) { 
    if (checkbox.checked === true) { 
     prices.push(amount); 
    } else { 
     remove(prices, amount); 
    } 

    var total = 0; 
    for (var i = 0, len = prices.length; i < len; i++) 
     total += prices[i]; 

    var min = prices.slice().sort(function(a,b){return a-b})[0]; 
    if(typeof min === 'undefined') min = 0; 

    var withDiscount = total - min; 
    var discountAmount = withDiscount - total; 

    document.querySelector("#value").innerHTML = "Total: $"+total+'<br>'; 
    document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>'; 
    document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>'; 
} 

실행 :

총 : $ (35)
할인 : $ -5
새로운 총 : $ (30)

calculateSectedDues({checked:true},10); 
calculateSectedDues({checked:true},20); 
calculateSectedDues({checked:true},5); 

이 출력을 제공합니다

JSFiddle


사용 확인란

<label><input type="checkbox" onclick="calculateSectedDues(this,5)" name="Scarf"> <span>Scarf</span><label><br> 
<label><input type="checkbox" onclick="calculateSectedDues(this,10)" name="Hat"> <span>Hat</span><label><br> 
<label><input type="checkbox" onclick="calculateSectedDues(this,20)" name="Jacket"> <span>Jacket</span><label><br> 

<span id="value">Total: $0<br>Discount: $0<br>New total: $0</span> 
+0

미안 @ DJDavid98. 사람들은 형식 ​​변경을 계속해서 제출했고, 나는 그것이 올바르게 표현되고 있다고 생각하지 않았기 때문에 몇 가지 다른 방식으로 다시 제출했습니다. 혼란스러운 점 사과 드립니다만, 정말로 고맙게 생각합니다. 그래서 당신이 말하는 곳에서 나는 그것을 실행합니다.CalculateSelectedDues ({checked : true}, 10); 모든 값을 나열하려고합니다. 예를 들어

+0

@Alfie_Fitz http://jsfiddle.net/DJDavid98/k5MXP/3/ – SeinopSys

+0

나를 위해 작동하지 않습니다; discountAmount는 항상 0입니다. – cfs

-1

나는 당신의 HTML이 어떻게 생겼는지 모르겠지만, 이런 식으로 뭔가가 작동합니다. jQuery를 사용하여 검사 된 모든 확인란을 선택하고 해당 확인란의 값을 합계에 추가하고 최소값을 추적합니다. 그런 다음 세 개의 값을 단일 객체로 반환합니다.

귀하의 확인란의 값이 항목의 가격이라고 가정합니다. 이는 사실 일 수 없습니다. 그렇지 않다면, 아이디어는 여전히 유효합니다. 올바른 가격을 얻으려면 더 많은 노력을 기울여야합니다.

function calculate() { 
    var total = 0, 
     discount = 0 
    ; 

    $('input[type="checkbox"]:checked').each(function() { 
     var val = parseFloat($(this).val()); 

     if(discount === 0 || val < discount) { 
      discount = val; // keep track of minimum 
     } 

     total += val; 
    }); 

    //return all three values in one object 
    return { 
     total: total, 
     discount: disount, 
     discountedPrice: (total - discount) 
    } 
} 
+0

-1 [tag : javascript] 질문에서 jQuery를 사용합니다. – SeinopSys

관련 문제