How to set datetime on datetime-local via jQuery

前端 未结 7 2017
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-18 15:43

I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?



        
7条回答
  •  北海茫月
    2021-02-18 16:01

    This component is messed up because it's not specified properly yet. Implementations are likely to be quirky as well.

    The right way to do it should be to pass a date object, with JS and DOM it would make no sense to not have this. Doing things with string manipulation is going to invoke Zalgo. Sooner or later it will break with the locale or timezone.

    I have looked for something like this and in Chrome 46 found:

    $('input[type=datetime-local]').prop('valueAsNumber', Math.floor(new Date() / 60000) * 60000); // 60seconds * 1000milliseconds
    

    If you don't remove the second and milliseconds they will show in the input field.

    There is a valueAsDate property as well but mysteriously:

    Uncaught DOMException: Failed to set the 'valueAsDate' property on 'HTMLInputElement': This input element does not support Date values.
    

    So they haven't finished implementing it yet or choose a bad name for that property (it shows as null even when something is set though).

提交回复
热议问题