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 trial
Angelic Sanoy
7,816 PointsJquery: Strange NaN Behavior
I am having a strange behavior everytime I select the dropdown first. Any idea how to fix the NaN issue? fyi, it works fine when I use the field first.
Here's the link: https://bit.ly/2KQszw6
<code> <div class="calculator-container"> <div class="calc-content">
<input type="number" value="" class="post_count" name="post_count" placeholder="No. of Posts"><br>
<select class="social_option">
<option value="18">Instagram</option>
<option value="35">YouTube</option>
<option value="3">Tumblr</option>
<option value="5">Facebook</option>
<option value="2">Twitter</option>
<option value="25">Blog</option>
<option value="10">Pinterest</option>
<option value="10">Snapchat</option>
<option value="50">Appearance Fee</option>
</select>
<div class="result"></div>
<span class="Calc_Result"></span>
<div class="upsell"> Enroll to our influencer marketing school to unlock the full influencer calculator feature! </div>
<button class="social-submit">Calculate The Costs</button>
</div>
</div>
$(document).ready(function(){
$('.upsell').hide();
$('.social_option, .post_count').change(function(){
var IsSelected = parseInt($(this).find (":selected").val(),10);
var PostCount = parseInt($('input').val(),10);
$('.social-submit').click(function() {
$('.result').text('Total Cost: $' +(PostCount)*(IsSelected));
$('.upsell').show();
});
});
});
</code>
1 Answer
Steven Parker
243,318 PointsThe "NaN" is the result of performing "parseInt" on an empty string. You could use an "isNaN" function to test it and do something else, or for a quck fix, just take advantage of empty strings being "falsey" and replace it with a zero:
var PostCount = parseInt($('input').val() || 0, 10);