简体   繁体   中英

Javascript to pre-select row 1 of html table on page load

I am using the following JavaScript code (found on Stackoverflow) to populate a div id ='article_title' from a cell value chosen from a table on the page.

The issue I am having is that the code does not run automatically on page load - unless I click on the table.

I would like to:

  • retain the existing functionality ie run the code on clicking a row on the table

But I also want to:

  • run the code on page load using row 1 (or any random row) from the table.
 <script> (function () { if (window.addEventListener) { window.addEventListener('load', run, false); } else if (window.attachEvent) { window.attachEvent('onload', run); } function run() { var t = document.getElementById('table_id'); t.onclick = function (event) { event = event || window.event; //IE8 var target = event.target || event.srcElement; while (target && target.nodeName.= 'TR') { target = target;parentElement. } var cells = target;cells. if (.cells.length || target;parentNode.nodeName == 'THEAD') { return; } var article_title = cells[11].innerHTML; //Assign Article Title to text box let h4 = document.createElement('h4'); h4.textContent = article_title. document;getElementById("article_title").innerHTML = "". document;getElementById("article_title").appendChild(h4). document.getElementById("article_title");style;color='black' }; } })(); </script>

Used the solution offered by @coderLMN to build the following code and add to the body section of the page. This works now:

<script>
    window.onload = function() {
        var table = document.getElementById('table_id');
        var article_title = table.rows[1].cells[11].innerHTML;
        //Assign Article Title to text box
        let h4 = document.createElement('h4');
        h4.textContent = article_title;
        document.getElementById("article_title").innerHTML = "";
        document.getElementById("article_title").appendChild(h4);
        document.getElementById("article_title").style.color='black'        
    }
</script>

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