2015-06-15 11 views
0

我有一個多於一個下拉列表的表單,如下所示。我可以看到如何獲取每個下拉列表的ID,但我無法弄清楚如何獲得實際使用的ID。請有人解釋如何做到這一點。如何確定使用哪個下拉列表

<div> 
    <select name="id[11]" class="pullDown" id="attrdrop0"> 
    <option class="pink" value="31`">No</option> 
    <option class="pink" value="32">Yes (+$40.00)</option> 
    </select> 
    </div> 

    <div> 
    <select name="id[10]" class="pullDown" id="attrdrop1"> 
    <option class="pink" value="31">No</option> 
    <option class="pink" value="32">Yes (+$150.00)</option> 
    </select> 
    </div> 

<script> 
$(function() { 
    $("#prices").change(function() { 
    console.log('A change was made'); 
    CalculatePrice(); 
    }); 
}); 

function CalculatePrice() { 
    var ttl_price = 0; 
    var id = ''; 

    $(":input.select, :input").each(function() { 
     var cur_price = $('option:selected', $(this)).text(); 
     ttl_price += cur_price;  

     id = $(this).attr('id'); 
     /*** What now ***/ 
    }); 
    SetPrice(id, ttl_price);  
} 
</script> 

回答

0

您可以將控件作爲參數傳遞給CalculatePrice。

$(function() { 
    $("#prices").change(function() { 
    console.log('A change was made'); 
    CalculatePrice(this); 
    }); 
}); 

function CalculatePrice(triggerObject) { 
    var ttl_price = 0; 
    var id = ''; 

    $(":input.select, :input").each(function() { 
     var cur_price = $('option:selected', $(this)).text(); 
     ttl_price += cur_price;  

     id = $(this).attr('id'); 
     /*** What now ***/ 
     if (triggerObject.id) {...} 
    }); 
    SetPrice(id, ttl_price);  
} 
</script> 
+0

謝謝,但我不認爲這會做我想要的。我試過了,它在CalculatePrice函數中顯示爲true,但它沒有標識下拉列表。 「#prices」是表單名稱,如果我在CalculatePrices函數中檢查了id變量,它只是顯示錶單名稱。我需要知道下拉ID。那可能嗎? – user3052443

+0

也許我不理解你的解決方案,或者我把最初的代碼弄糊塗了,但是在我展示的代碼是[code]

[/code],所以當調用change函數時,(this)指向表單,而不是下拉菜單。在CalculatePrice中,代碼循環遍歷表單中的所有元素。我看不到爲每個下拉菜單創建更改功能的另一種方式,因爲代碼將在多個頁面上,所以這是一個未知數。 – user3052443

+0

然後你可以使用event.target:https://api.jquery.com/event.target/ – Hopesun

相關問題