treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Help Creating A Dynamic Credit Card Dropdown

  • Hello All,

    I am trying to create a dynamic dropdown that will take the current year and iterate another 15 years to it so I don't have to continue to update the credit card year dropdown field. I have successfully built the for loop but cannot seem to figure out how to put this inside a select tag.

    Any help would be great!

    Here is the for loop that iterates the date. Here is my CodePen

    var date = new Date().getFullYear();
    var length = date + 16;
    
    for(var i = date; i < length; i++){
      document.write("<br/>" + i + "<br/>");
    }
    
  • Here you go: http://www.codepen.io/anon/pen/IxsiJ

    You really had the right idea, you just really don't want to use document.write() in that case. I've written up two methods above -- one with vanilla JS, and one using jQuery.

    First, you need to set a default option in your select in the HTML (I also cleaned that up and added a label, because I'm picky like that).

    Then, with jQuery, it's super easy -- you just append additional option tags with your variable filling in the value. Same with plain-jane JS, except you have to use document.getElementById() and .insertAdjacentHTML().

  • Heh, thanks, @Paulie_D.

    One thing I might mention, though, @jcoder, is that this is probably something best done in the backend, or at least with proper fallback. I say that because with this method, if the client has JavaScript disabled (small use-case, yes, but a higher percentage than you might expect), they're going to get essentially a blank dropdown.

    Hence, this may be better done with PHP or similar. Just something to consider.

  • @JoshBlackwood, Thanks for the help and multiple versions! That's a good point on JavaScript being disabled, but I learned some new stuff : )

    Thanks!