[英]Get value of input type=date as a string
我想從日期字段中提取值,但它不起作用。 我以這種方式添加輸入:
var question0 = "<div id='0'><p>Please, enter the date: </p><br>"
+ "<input type=\"date\" id=\'contractdate\'></input><br></div>";
這是我嘗試接收值的方式:
var text_Contract_Date = document.getElementById('contractdate').value;
//tried the code below, but didn't work
// var text_Contract_Date = document.getElementById('contractdate').valueAsDate;
// var text_Contract_Date = new Date(document.getElementById('contractdate').valueAsDate);
所以,我想從輸入中獲取值作為字符串,使用純 JavaScript,因為那樣它將用於填充文檔。
嘗試這個
var dateEntered = new Date(text_Contract_Date);
沒有足夠的信息來解決這個問題,所以我只能猜測您可能以錯誤的方式將變量插入 DOM。 如果我調用document.body.append(question0)
,則只顯示文本而不顯示標簽。 嘗試將question0
變量的內容移動到您的 html 文件中,然后將 onchange 處理程序添加到您的輸入中,並修改您的 .js 文件,如下所示
function handleChange(event){ // here you can do whatever you want with the value of the input alert(event.target.value) }
<input type="date" id='contractdate' onchange="handleChange(event)"></input>
如果你非常想在 Javascript 中創建 HTML,你必須這樣做:
// create div and assign id to it
const myDiv = document.createElement("div")
myDiv.id = '0'
// create p and set its contents
const myP = document.createElement("p")
p.textContent = "Please, enter the date: "
// create input, assign id to it and set its type to date
const myInput = document.createElement("input")
myInput.id = 'contractdate'
myInput.type = "date"
// put everything in your document
myDiv.appendChild(myP)
myDiv.appendChild(myInput)
document.body.appendChild(myDiv)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.