Reputation: 720
I am working within miva system so lets just say its a nightmare. I have the following code that I have to work with
<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>
My only option within this store is to work with jquery. I am fairly new to jquery so I would appreciate any help you are willing to give me.
On page load I want it to select the cheapest option. The method I was thinking of was to somehow collect the text within the option parse out the price then compare and select the lowest value. If you have something that may help I thank you ahead of time.
Upvotes: 0
Views: 4549
Reputation: 14187
Instead of use using .each
and those messy workaround, you can achieve what you need in 3 lines ;-)
Live Demo: 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);
Upvotes: 0
Reputation: 5231
$("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);
});
i quickly put this together which get the price on its own from each text so you can sort it. hope this helps
Upvotes: 0
Reputation: 207901
Try this 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);
Basically this loops through the option text values, splits them and parses them into floating points, then finds the lowest value and selects it.
Upvotes: 2