输入字段中的显示值不适用于JavaScript

时间:2017-07-12 07:53:51

标签: javascript jquery

我试图在输入字段中使用vanilla Javascript显示一个值,但奇怪的是,在我使用JQuery之前它没有工作

香草JS的例子



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;
} 
var today = dd+'/'+mm+'/'+yyyy;
document.getElementsByName("plan_date").value = today;
&#13;
<input name="plan_date" type="text">
&#13;
&#13;
&#13;

这里有与JQuery相同的例子

&#13;
&#13;
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;
} 
var today = dd+'/'+mm+'/'+yyyy;
$('input[name=plan_date]').val(today);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="plan_date" type="text">
&#13;
&#13;
&#13;

有人可以向我解释我的错误是什么吗?

4 个答案:

答案 0 :(得分:1)

你几乎完成了。你错过提到[0]。因为name属性是元素的多个选择器。所以你可以提到0.然后只有它的目标是第一个元素

&#13;
&#13;
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;
} 
var today = dd+'/'+mm+'/'+yyyy;
document.getElementsByName("plan_date")[0].value = today;
&#13;
<input name="plan_date" type="text">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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;
} 
var today = dd+'/'+mm+'/'+yyyy;
document.getElementsByName("plan_date")[0].value = today;
<input name="plan_date" type="text">

document.getElementsByName returns an array of element with same name, so access like this document.getElementsByName("plan_date")[0].value = today;

答案 2 :(得分:0)

getElementsByName("plan_date") returns an array

try with

document.getElementsByName("plan_date")[0].value = today;

答案 3 :(得分:0)

It's because getElementsByName returns an array. So you could use document.getElementsByName("plan_date")[0].value = today; or add an id to the element like so:

document.getElementById("element_id").value = today