Ares_SVX
Ares_SVX

Reputation: 43

Copy the date text to textfield using javascript

I want to copy the date text to textfield. when i click the button to copy, the result in textfield is undefined. Can someone help me about this problem?

function ShowHideDiv() {

  var date1 = document.getElementById("datetime");
  var text1 = document.getElementById("textfield1");

  text1.value = date1.value;
}

var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toISOString().substr(0, 10);
<p name="datetime" id="datetime" style="position:absolute;margin-top:80px;font-weight:bold"><span id="datetime" name="datetime" id="date_now"></span></p>

<input type="text" id="textfield1" name="textfield1">

<input type="submit" onclick="ShowHideDiv()" value="copy">

Upvotes: 0

Views: 82

Answers (2)

cdoshi
cdoshi

Reputation: 2832

You are setting the date as innerHTML of the paragraph tag. So, instead of date1.value use date1.innerHTML. Check the working snippet:

function ShowHideDiv() {

  var date1 = document.getElementById("datetime");
  var text1 = document.getElementById("textfield1");

  text1.value = date1.innerHTML;
}

var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toISOString().substr(0, 10);
<p name="datetime" id="datetime" style="position:absolute;margin-top:80px;font-weight:bold"><span id="datetime" name="datetime" id="date_now"></span></p>

<input type="text" id="textfield1" name="textfield1">

<input type="submit" onclick="ShowHideDiv()" value="copy">

Upvotes: 1

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3541

You need to use innerHTML which will provide the inner content of selected element by id.

function ShowHideDiv() {
        var date1 = document.getElementById("datetime");
        var text1 = document.getElementById("textfield1"); 
        text1.value =  date1.innerHTML;
    }
    var dt = new Date();document.getElementById("datetime").innerHTML = dt.toISOString().substr(0, 10);

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

Also you need to use button instead of using input with type submit, since you are not submitting the data. This approach will be more fast and better.

<button type="button" onclick="ShowHideDiv()" >Copy</button>

Upvotes: 0

Related Questions