• # February 21, 2013 at 10:57 am

    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]( “CodePen”)

    var date = new Date().getFullYear();
    var length = date + 16;

    for(var i = date; i < length; i++){
    ” + i + “

    # February 21, 2013 at 11:23 am

    This reply has been reported for inappropriate content.

    Here you go:

    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().

    # February 21, 2013 at 11:29 am



    # February 21, 2013 at 11:35 am

    This reply has been reported for inappropriate content.

    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.

    # February 21, 2013 at 11:50 am

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


    # August 20, 2013 at 10:32 am

    Hi @JoshBlackwood, this was exactly what i was looking for even though it’ll probably get taken out since we’ll have nothing if the user disables Javascript but I wanted to know how you would do this for the months category. I’m new to JS so sorry if it’s simple I just don’t know how to do it and there’s not a lot online about credit card expiry dropdowns, i thought there would be. thanks in advance.

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.