简体   繁体   中英

document.getElementById doesn't get newly entered HTML text input value

I use the following code.

The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".

The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.

If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".

<html> 
<head> </head> 
<script type="text/javascript">

function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
 <body> 
  <div id="printThis" name="printThis">
   <textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
  </div>

  <input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>

In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.

document.location.reload(true);
window.top.location=window.top.location;

The production version does have jQuery available too.

first of all you are trying to get innerHTML of the div, instead of the actual textarea. secondly instead of trying to get innerHTML try using value.

http://jsfiddle.net/qdymvjz8/

<div id="printThis" name="printThis">
   <textarea id="textarea1" cols="1" rows="10">cake</textarea>
  </div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">

function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}

If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.

function printFunction(divName) {
  var printContents = document.getElementById(divName),
    childItemCount = 0,
    stringToPrint = '';

 for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
    stringToPrint += printContents.children[childItemCount].value;
 }

 console.log(stringToPrint);
 //Now call a script to print (not included)
}

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