2014-07-14 1 views
0

그래서 선택 값을 기반으로 변수를 변경하고 변경할 때 실시간으로 표시하려고합니다. 나는 이미 변수를 정적 방식으로 설정하여 작동시키고 있지만 선택 값이 변경되거나 증가하면 변수를 변경하는 방법을 이해하지 못합니다.자바 스크립트 onchange - 선택 값을 기반으로 변수를 변경하십시오.

이 경우 수량을 기준으로 가격을 변경하려고합니다. 수량이 X보다 큰 경우 가격이 Y로 변경됩니다. 자바 스크립트에 익숙하지 않다는 것을 명심하십시오. 따라서 기본 답변을 유지하십시오.

이 내 현재 코드입니다 :

<label>Single User</label> 
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)"> 
    <option value="0">0</option> 
    <option value="1">1</option> 
</select>&nbsp;&nbsp;<font size="4"><b>@ $34.95/mo</b></font> 

자바 스크립트

var size = 36; 
var cart = new Array(); 

for (var j = 0; j < size; j++) //initialize cart to all 0 
    cart[j] = 0; 

function changed(me, id, price) { 
    var amount = me.options[me.selectedIndex].value; //quantity passed 
    var t_price = amount * price; //multiply operation 
    cart[id] = t_price; //update cart array 
    update_spans(); 

    document.getElementById(id).value = amount; //update quantity for final page 
} 
function update_spans() { 
    put("cart0", cart[0]); 
} 
function put(name, price) { 
    try { 
     price = (Math.round(price * 100)/100); //round 
     price = price.toFixed(2); //two decimal places 
     document.getElementById(name).innerHTML = price; //put into span 
    } catch (err) { 
     //error 
    } 
} 
+1

내 대답을 확인하고 유용하다고 판단되면 알려 주시기 바랍니다 :) – hex494D49

+0

이것은 정확하게 내가하려는 일이 아닙니다. 다시 읽으면 나는 그것을 잘못 설명했다. 더 많은 수량으로 단가를 변경하려고합니다. 수량이 X보다 높으면 단가가 더 낮은 가격으로 변경됩니다. 수량 할인! – Arringar

+0

업데이트 된 답변을 확인하십시오. 보시다시피, 나는 할인을위한 배열을 추가했습니다. 배열의 인덱스는 해당 수량에 대한 할인 값을 가지므로, discount [0] = 0 % discount는 수량 0에 대해 할인이 없음을 의미합니다. 또한 discount [1] = 5 % 즉, 수량 1의 경우 5 % 할인 등이 있음을 의미합니다. 물론이 값을 변경하고 수량 2 이상에 대해 할인을 정의한다고 가정 해 봅시다. 이 경우 할인 배열은 [0, 0, 5, 10, 15, 20, 25]처럼 보일 것입니다 ... 분명합니다 : – hex494D49

답변

1
세계에 법과를 확인

// HTML 
<label>Single User</label> 
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)"> 
    <option value="0">0</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option>  
</select> 
&nbsp;&nbsp; 
<span id="price">@ $34.95/mo</span> 

// JavaScript (this is all you need) 
var size = 36, cart = []; 
var discount = [0, 5, 10, 15, 20, 25, 50]; 

for(var j = 0; j < size; j++) cart[j] = 0; 

function changed(me, id, price){ 
    var amount = me.options[me.selectedIndex].value; 
    var p_discount = amount * price * (discount[me.selectedIndex]/100); 
    var t_price = (amount * price) - p_discount; 
    cart[id] = t_price; 

    r_price = (Math.round(t_price*100)/100); 
    r_price = r_price.toFixed(2); 

    document.getElementById('price').innerHTML = '@ ' + r_price + '/mo'; 
} 

아래의 코드를 사용하여 HTML과 자바 스크립트 부분을 변경

HTML 킹 jsBin

+0

이것은 내가 필요한 것입니다. 고맙습니다 @ hex494D49 !!! – Arringar