[英]Setting the input value of a form element from javascript
我的表單元素看起來像
<div class="modal fade" id="modal-xl">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You Can Edit This Item</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form role="form" id="modal-form">
<div class="card-body">
<div class="form-group">
<label for="receivingdate">Receiving Date</label>
<input type="date" class="form-control" id="receivingdate" placeholder="Select Receiving Date" required>
</div>
從 javascript 我只想將receivingdate
設置為x/x/x
var form = document.getElementById('modal-form').getElementsByClassName('form-group');
不知道為什么這不起作用。
var form = document.getElementById('modal-form').getElementsByClassName('form-group');
不起作用,因為您的document.getElementById('modal-form')
獲取特定元素而.getElementsByClassName('form-group')
不能用於獲取該元素的子元素。 此外,表單變量將簡單地保存從文檔中檢索到的元素。
如果您絕對需要在#modal-form 下獲取所有 .form-group 元素,則可以使用
var elements = document.querySelector("#modal-form .form-group");
如果您只是想設置 #receivingdate 日期元素,則可以使用該元素的 value 屬性。
document.getElementById("receivingdate").value = "2019-12-10";
請注意,這將需要yyyy-MM-dd
格式的字符串。 您不能將該框從字面上設置為x/x/x
,但將其設置為上述值將根據您的語言環境為您提供10/12/2019
或12/10/2019
。
如果您只是希望它默認為今天的日期,那么您可以使用
document.getElementById("water-volume").value = new Date().toLocaleDateString('en-CA');
其中 en-CA 將今天的日期設置為加拿大英語日期格式的字符串格式,這恰好是日期元素所需的格式。
如果要檢索當前日期,只需使用
var date = document.getElementById("receivingdate").value;
你會把它放在一個像 on change 這樣的事件處理程序中。
如果你只是想獲得接收日期的價值。試試這個
document.getElementById('receivingdate').addEventListener('change', function(e) {
var form = document.getElementById('receivingdate').value;
console.log(form)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.