简体   繁体   中英

How can we change the HTML table contents dynamically using javascript?

how can I dynamically change the html table contents if the table is in a pop up which will be displayed while pressing a button?

I know we can change the content using the below function

function change(){
    var x=document.getElementById('tbl').rows
    var y=x[0].cells
    y[0].innerHTML="NEW CONTENT"
}

But it is only possible when the table is on the same window. In case of pop up it will not change.

If you are creating the pop up with a hovering div, then you can simply use document.getElementById() and pass it the element you want to manipulate. If you are spawning a child window you need to specify the name of that window in place of document.

var x = window.open();

var tableRef = x.getElementById();

You can control the state of the child window by calling its object reference, in the same way you do with document.

What kind of popup are you creating? Is this opening a new window or just a div within the same window, like jquery dialog? The latter can be used just the way you point out. The former will require you to send the value to the server as a part of the GET or POSt method and then server will have to send the populated table. Does someone know a better way? I am curious too.

You can access the elements in a window you open using windowRef.document.getElementById(...) like so:

<script type="text/javascript">
// Global used here, would use in a closure in RL
var popupWindow;

function popWin() {
  var content = '<title>Popup window</title>' +
                '<table id="tbl">' +
                '<tr><td>Row 0 Cell  0<td>Row 0 Cell  1' +
                '</table>';
  var newWin = window.open('','newWin');
  newWin.document.write(content);
  newWin.document.close();
  return newWin;
}
</script>
<p>Some examples of accessing the content of a popup
   created by script in this page</p>

<input type="button" value="Open popup" onclick="
  popupWindow = popWin();
">
<input type="button" value="change table content" onclick="
  if (popupWindow) {
    var tbl = popupWindow.document.getElementById('tbl');
    tbl.rows[0].cells[0].firstChild.data = 'hey hey!';
  }
 ">
 <input type="button" value="Close popup" onclick="
   if (popupWindow) {
     popupWindow.close();
     popupWindow = null;
   }
 ">

However it's worth noting that most users hate popups, will block them unless they are initiated by a user action (click or similar), and may close them without you knowing. Also, you can only do the above with windows that you open, you can't randomly change the content, or even access, any window.

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