Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEric Ewers
13,976 PointsSplit String with JQuery
How can I split the values from a select box when they have a | in between them. Like so: value="100|200", but I only want to return the 200.
Please see CodePen example:
1 Answer
Juan Martin
14,335 PointsHello my friend,
I did it this way for JavaScript:
$(".product").change(function() {
var combined = 0;
combined = parseInt(this.value.split('|')[1]); // here you'll get the second value, [0] will get the first one
$("#result").html(combined);
}).trigger("change");
For the HTML, I've added this to the first option value (0|0):
<select name="product1" class="product">
<option value='0|0'>0</option>
<option value='1|100'>1 ($100)</option>
<option value='2|200'>2 ($200)</option>
<option value='3|300'>3 ($300)</option>
<option value='4|400'>4 ($400)</option>
<option value='5|500'>5 ($500)</option>
</select>
<p><strong>
$<span id="result">0</span>
</strong></p>
<!-- End Total Price -->
Hope this helps :)
Eric Ewers
13,976 PointsEric Ewers
13,976 PointsThis works, thank you so much!
You even cleaned up the code a bit.
Juan Martin
14,335 PointsJuan Martin
14,335 PointsYou're welcome my friend,
You can even clean the JS a little bit more like this:
There's no need of initializing combined as 0, as well as for the parseInt function to use it, as it's just text what you're showing.
And you can even clean it more like this:
Regards :)
Eric Ewers
13,976 PointsEric Ewers
13,976 PointsI've done some more testing. When using multiple selects, the code has to be like this:
Otherwise, the sum of the values don't add up...it will keep switching to the last selected value.
Juan Martin
14,335 PointsJuan Martin
14,335 PointsI didn't know about that, I thought it was just for "displaying purposes" hehe, you're right!