简体   繁体   中英

javascript - filling 2 text boxes with dates

I'm trying to create a drop down list that will automatically enter dates into text fields.

Filling the text fields is easy, but I don't know where to start when trying to figure out how to dynamically filling those text fields with dates such as "first day of the month through today" or "from the first of the year through today".

This is what I've got so far:

javascript

<script>
$(document).ready(function() {
$("#datetype option").filter(function() {
    return $(this).val() == $("#datepickstart").val();
    return $(this).val() == $("#datepickend").val();
}).attr('selected', true);
$("#datetype").live("change", function() {
    $("#datepickstart").val($(this).find("option:selected").attr("value"));
    $("#datepickend").val($(this).find("option:selected").attr("value"));
    });
});
</script>

html

<select id="datetype" name="datetype"> 
<option value="">Please select...</option> 
<option value="LBD">LBD</option> 
<option value="MtD">MtD</option> 
<option value="YtD">YtD</option> 
</select>

<input type="text" id="datepickstart" name="datepickstart" value="">
<input type="text" id="datepickend" name="datepickend" value="">

To achieve expected result use below option

$(document).ready(function() {
    $("#datetype option").filter(function() {
        return $(this).val() == $("#datepickstart").val();
        return $(this).val() == $("#datepickend").val();
    }).attr('selected', true);

    var d = new Date();
    var today = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
    var fdm = (d.getMonth() + 1) + '/01/' + d.getFullYear();

    var fdy = '01/01/' + new Date().getFullYear();

    $("#datetype").on("change", function() {
        var selectedVal = $(this).find("option:selected").attr("value");
        if (selectedVal == 'LBD') {
            $("#datepickstart").val(today);
            $("#datepickend").val(today);
        }
        if (selectedVal == 'MtD') {
            $("#datepickstart").val(fdm);
            $("#datepickend").val(today);
        }
        if (selectedVal == 'YtD') {
            $("#datepickstart").val(fdy);
            $("#datepickend").val(today);
        }

    });
});

http://codepen.io/nagasai/pen/begRax

LBD will fill today's date in both fields
MtD will fill Month's first date and second field will have today's date
YtD will fill Year's first date and second field will have today's date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM