2012-10-05 157 views
0

我在miva系统中工作,所以让我们只是说它的噩梦。我有以下代码,我必须与jquery自动选择下拉值

<select name="ShippingMethod"> 
<option value="mvfedexsoap:FEDEX_2_DAY">FedEx 2Day® ($15.91)</option> 
<option value="mvfedexsoap:GROUND_HOME_DELIVERY">FedEx Home Delivery® ($13.36)</option> 
<option value="mvfedexsoap:PRIORITY_OVERNIGHT">FedEx Priority Overnight® ($20.15)</option> 
<option value="mvfedexsoap:STANDARD_OVERNIGHT">FedEx Standard Overnight® ($18.41)</option> 
</select> 

我在这家商店的唯一选择是使用jQuery。我对jQuery相当陌生,所以我会很感激你愿意给我的任何帮助。

在页面加载中我希望它选择最便宜的选项。我想到的方法是以某种方式收集选项中的文本,解析出价格,然后比较并选择最低值。如果你有什么可以帮助的,我会提前谢谢你。

+0

您在任何方式能够改变HTML?如果您可以将价格放在数据字段中,它会对您有所帮助。如果这是可能的,我有一个简单的解决方案。 –

+0

Miva不允许你编辑这个系统 – James

+0

@James检查我的答案,改进版本。 –

回答

2

试试这个jsFiddle example

var idx = 0; 
var lowest = 9999; 
$('select[name=ShippingMethod] option').each(function(i) { 
    val = parseFloat($(this).text().split('$')[1]); 
    if (val < lowest) { 
     idx = i; 
     lowest = val; 
    } 
}); 
$('select[name=ShippingMethod] option:eq('+idx+')').prop('selected', true); 

基本上这个循环通过选项文本值,分裂并将其解析到浮点,则认定的最低值并选择它。

0
$("option").each(function(index) { 
// alert(index + ': ' + $(this).text()); 
var text = $(this).text();//get text for each option 

    var price = text.split("$");//split text at the $ symbol 

    var final_price = price[1].replace(/[()]/g,'');//remove all remaining parenthesis from string 



    alert(final_price); 

}); 

我很快把它放在一起,它从每个文本中获得价格,所以你可以对它进行排序。希望这有助于

0

而不是使用.each和那些乱七八糟的解决方法的使用,可以实现你在3线需要什么;-)

现场演示:http://jsfiddle.net/oscarj24/ZgEbH/

prices = $("select[name=ShippingMethod] option").map(function(){ return parseFloat($(this).text().split('$')[1]); }).get(); 
lowPrice = Math.min.apply(Math, prices); 
$("select[name=ShippingMethod] option:contains('" + lowPrice + "')").prop("selected", true);