简体   繁体   中英

How can I pass date/text to <input type="date">?

I'm trying to set text in input date but nothing shows there. Is it something wrong with data type?

<!DOCTYPE html>
<html>
<body>

<table>
    <tr>
        <td id="invoice">
        2020-09-22
        </td>
    </tr>
</table>    

<select id="decisionList">
  <option></option>
  <option>Payment date</option>
</select>

<div id="choice">
</div>



<script>

document.addEventListener("change", function () {

  var decisionList = document.getElementById("decisionList");
  var selectedOptionIndex = decisionList.options[decisionList.selectedIndex].index;  
  
  var invoiceDate = document.getElementById("invoice");
  var invoiceDateText = invoiceDate.textContent;
  
  var finalChoice = document.getElementById("choice");

  switch(selectedOptionIndex) {
    
    case 0:
        finalChoice.innerHTML='<input type="date">'
    break;
   
    case 1:
        finalChoice.innerHTML='<input type="date" value="' + invoiceDateText + '">' //here is a problem
    break;

    default:
    
    finalChoice.innerHTML=''
    
  }
  
})

</script>

</body>
</html>

I also tried to create new Date based on text I'm passing:

  var newDate = new Date(invoiceDateText);

but also doesn't work. As you can see I'm passing 2020-09-22 (from td) so where is the problem?

The variable invoiceDateText contains white spaces and therefore is not parsed correctly.

You can update that part to the following.

 var invoiceDateText = invoiceDate.textContent.trim();

日期应该是一个字符串,格式为YYYY-MM-DD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM