views:

82

answers:

3

Hi,

I have the following drop down menu:

<select id="target">
    <option value="0">Zero ($123.45)</option>
    <option value="1">One ($99.99)</option>
    <option value="2">Two ($4.50)</option>
</select>

Using jQuery, how can I select the contents of the selected option's () brackets, i.e. 123.45, 99.99 or 4.50?

So far I have:

$("select#target option:selected").contents();

That just gives Zero ($123.45) or equivalent though. How can I filter it further to get the number I'm looking for?

Thanks in advance.

+4  A: 

Try:

var a = $("select#target option:selected").contents();
var bracketed = a.replace(/\(([^)]*)\)/g, "$1");

Or, if you don't want to use a regex:

var a = $("select#target option:selected").contents();
var bracketed = a.split('(')[1].split(')')[0];
Lucas Jones
+3  A: 

I think that the most idiomatic way to do this with jQuery is

$("#target :selected").text().match(/\((.+)\)/).pop()

Regular expressions are usually the best way to match text in Javascript, and this style of code conforms to the usual jQuery method chaining style, doesn't introduce any superfluous local variables, and doesn't include an ugly index dereferencing operation. I've also written the selector in more compact form.

Rich
+3  A: 

You could also just use those dollar values as the value attribute for each:

<option value="$123.45">Zero ($123.45)</option>
    etc...

then use this jQuery to get it:

var a = $('select#target option:selected').attr('value');
carillonator
I like this suggestion. Parsing text works, but seems a bit less flexible down the road in case of changes (unless go nuts testing variations with your regex). I'd probably suggest using a class of priceXXXXX-XX and parse that, as the class can be defined more specifically and wouldn't likely be changed as much as text would be.
DA