2013-04-15 29 views
1

我有一個合理簡單的輸入集合,用於下訂單。回聲輸入項目

基本上,它會計算它們的數量*價格。

但是,在提交按鈕附近的底部,我想顯示總價格加上他們訂購的物品。有沒有使用JQuery或類似的方法,我基本上可以回顯他們在數量字段中放置數字的項目的關聯h6內容?

我已經有總成本工作正常。

<tr> 
    <td> 
     <h6>Title</h6>Text. 
    </td> 
    <td id="price_item_1" class="menuprice">$PRICE</td> 
    <td class="quantitynum"> 
     <input type="text" name="qty_item_1" id="qty_item_1" value="0" /> 
    </td> 
    <td id="total_item_1" class="runningtl"></td> 
</tr> 
+0

你在哪裏計算數量*價格? – asifrc

+0

我有一個JavaScript函數,可以計算數量*價格和類runningtl的地方。但是,如果數量大於0,我不知道如何顯示h6標記內容。 – Palemo

+0

您可以發佈計算代碼還是鏈接[jsfiddle](http://jsfiddle.net)? – asifrc

回答

0

假設你計算每次的數量值的變化,你可以做的是,你計算總,檢查的數量值的函數內部總,並採取相應的行動:

if (quantity > 0) 
    $("h6").show(); // assuming there is only one h6 in the page, otherwise you have to add ids to each h6 
else 
    $("h6").hide(); 
+0

類型,但在表單底部有一個摘要,顯示總數並詢問他們的姓名等。每個項目都有一個與其關聯的h6標籤。例如,我可以使用$('h6')。html()來回顯標籤,但不知道如何包裝併爲每個項目重複此操作,數量> 0 – Palemo

0

我會提出一個建議,而不是爲每個輸入查看不同的元素,將標題文本存儲爲input本身的屬性。 title屬性是完美的。

考慮到這一點,下面的代碼片段應該工作:

HTML:

爲清楚起見稍微簡化。我已經爲表單,輸入和摘要元素添加了類。

<form class="order-form"> 
    <table> 
    <tr> 
     <td><input type="number" class="quantity" title="Product 1"/></td> 
    </tr> 
    <tr> 
     <td><input type="number" class="quantity" title="Product 2"/></td> 
    </tr> 
    <tr> 
     <td><input type="number" class="quantity" title="Product 3"/></td> 
    </tr> 
    </table> 
    <div class="order-form-summary"></div> 
</form> 

的Javascript:

$(function(){ 
    // Find all of the DOM elements we're interested in: 
    var form = $('form.order-form'), 
     output = form.find('.order-form-summary'), 
     inputs = form.find('input.quantity'); 

    // Bind a custom event handler to the form, that collects the titles from the 
    // inputs with a value > 0 
    form.bind('updateSummary', function(){ 

    // Collect the titles into an array 
    var summaries = $.map(inputs, function(e){ 
     var input = $(e); 
     if (parseInt(input.val()) > 0){ 
     return input.attr('title'); 
     } 
    }); 

    // Update the output element's HTML with the array, joined to a string with commas. 
    output.html(summaries.join(', ')); 
    }); 

    // Fire the update event whenever chance, key-up or blur occurs on any input 
    inputs.on('change keyup blur', function(){form.trigger('updateSummary')}); 

    // Fire it on load to get the correct starting values (in case any inputs are already filled) 
    form.trigger('updateSummary'); 
}); 

這個代碼可以凝結,但我的目的是把它的可讀性。這裏有一個小例子:https://jsfiddle.net/ejwLy5x8/