jquery自动选择下拉值

时间:2012-10-05 16:00:44

标签: jquery

我在miva系统中工作,所以让我们说它是一场噩梦。我有以下代码,我必须使用

<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相当新,所以我很感激你愿意给我的任何帮助。

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

3 个答案:

答案 0 :(得分: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);

基本上,它循环选项文本值,拆分它们并将它们解析为浮点,然后找到最低值并选择它。

答案 1 :(得分: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);

});

我很快将这些放在一起,从每个文本中获取价格,以便您对其进行排序。希望这有帮助

答案 2 :(得分: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);
相关问题