在 jquery 中设置 <input type="date"... 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16889933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:58:47  来源:igfitidea点击:

Set the value of <input type="date"... in jquery

javascriptjqueryhtmldate

提问by Hoser

Don't understand why this isn't working. I have a simple 'input type="date"' field as such....

不明白为什么这不起作用。我有一个简单的 'input type="date"' 字段......

<input type="date" name="Date"/>

And I'm trying to set the value to todays date whenever the page loads with this function...

每当使用此功能加载页面时,我都会尝试将该值设置为今天的日期......

function setDate(date){
    z=$(date).attr('value');

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm} 
    today = yyyy+'-'+mm+'-'+dd;     

    $(date).attr('value',today);
}

I've done the normal debugging and I know this function is being called and I know that the variable 'today' does in fact hold todays date in the form 'yyyy-mm-dd'. I have tried doing all different types of date formats (dd/mm/yyyy, dd-mm-yyyy, etc.)

我已经完成了正常的调试,我知道正在调用这个函数,我知道变量“今天”确实以“yyyy-mm-dd”的形式保存了今天的日期。我尝试过所有不同类型的日期格式(dd/mm/yyyy、dd-mm-yyyy 等)

Any idea why this isn't working?

知道为什么这不起作用吗?

回答by Sushanth --

For input just use .val()

对于输入只需使用.val()

To read the value

读出的值

  z=$(date).val();

To set the value

设置的值

$(date).val(today);

回答by mixel

$('input[name=Date]').val(today);