'Adding buttons dynamically using JavaScript

I am trying to create a simple html page some dynamic buttons. This is what I did so far:

<HTML>
<BODY  bgColor="#d4d4d4"  onload="OnLoad()" >

<script language = "javascript">

function OnQuery()
{
  alert("Query");
}
function OnLoad()
{
  document.write("<INPUT onclick=\"OnQuery()\" type=\"button\" value=\" Search \" name=\"querybtn\" />");
}
</script>
</BODY>
</HTML>

As you can guess from code I am very very new to JavaScript. The button 'Search' is getting added but when clicked OnQuery is not called. What am I doing wrong? This is a simple prototype code which is intended only for IE.



Solution 1:[1]

Changed the document.writes to using document.createElement to do the Dom creation

function OnQuery()
{
    alert("Query");
}

function OnLoad()
{
    var Objs = new Array();
    var xmlInput = "<QueryResult>Some values</QueryResult>";

    var doc = xmldso.XMLDocument;
    doc.loadXML(xmlInput );

    var x = doc.getElementsByTagName("QueryResult");

    for(i=0; i < x.length; ++i)
    {
        Objs[i] = new MyObject(x[i]);
    }


    //Create the table element
    var table = document.createElement("table");
    table.setAttribute("border",1);

       for(i=0; i < Exams.length;++i)
       {
            //Create the row element
            var row = document.createElement("tr");
            //Create the 2 columns
            var col1 = document.createElement("td");
            var col2 = document.createElement("td");

            //Create the checkbox input
            var chkId = "Row" + i;            
            var chkIdInput = document.createElement("input");
            chkIdInput.setAttribute("type","checkbox");
            chkIdInput.id = chkId;

            //Add the checkbox to the column
            col1.appendChild(chkIdInput);

            //Set the text of second column
            col2.textContent = Objs[i].Prop1;

            //Add columns to the row
            row.appendChild(col1);
            row.appendChild(col2);

            //Add the row to the table
            table.appendChild(row);
       }
       //Add the table to the body
       document.body.appendChild(table);

       //Create the search button
       var searchBtn = document.createElement("input");
       //Set the attributes
       searchBtn.setAttribute("onclick","OnQuery()");
       searchBtn.setAttribute("type","button");
       searchBtn.setAttribute("value","Search");
       searchBtn.setAttribute("name","querybtn");
       searchBtn.style.marginLeft = "20px";
       searchBtn.style.marginTop = "20px";
       //Add the button to the body
       document.body.appendChild(searchBtn);
}


function OnUnload()
{
}

Works in jsfiddle in IE 10 & 9 didn't check lower versions

JSFiddle

Solution 2:[2]

Don't ever use document.write() - it's a really ugly legacy bit of functionality.

HTML tags (since about v4 of html) should be in lower case. There's other things about the code wich are messy - but there is a seperate a StackOverflow site for code review.

There's nothing here which is MSIE speciic - and I strongly encourage you not to wite MSIE specific code - if you write code for Firefox or webkit, then you'll find it much more portable across different targets (including MSIE).

Trying again....

<html>
<script>
function OnQuery() {
    alert("Query");
}
function OnLoad() {
    var t=false;
    if (t = document.getElementById("placeholder")) {
        t.innerHTML="<INPUT onclick=\"OnQuery()\" type=\"button\" value=\" Search \" name=\"querybtn\" />";
    }
}
if (window.addEventListener) {
     window.addEventListener('load', OnLoad, false);
} else if (window.attacheEvent) {
     window.attachEvent('onload', OnLoad);
}
</script>
<body  style="background-color: #d4d4d4">
<div id="placeholder"></div>
</body>
</html>

While you could explicitly use the DOM createElement and add node stuff - it gets messy and slow when working with complex constructs - HTML fragments and innerHTML are more flexible and faster.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Evans
Solution 2