tags:

views:

30

answers:

4

I want to do something when 2 document.write() statements have successfully occured. I tried the following but it didn't work:

        function loadFields() {
            var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
            var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
        }

        if (loadFields()) {
            alert('both items have loaded.');
        }

I also tried this and again same result:

        var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
        var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");

        if (load1 && load2) {
            alert('both items have loaded.');
        }
+3  A: 
    function loadFields() {
        document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
        document.write("<input type='text' name='couponType' value='"+couponType+"' />");
        return true;
    }

    if (loadFields()) {
        alert('both items have loaded.');
    }

OR

    function loadFields() {
        document.write("<input id='StoreLocation' type='text' name='StoreLocation' value='"+storeLocation+"' />");
        document.write("<input id='cuponType' type='text' name='couponType' value='"+couponType+"' />");
    }

    if (document.getElementById("StoreLocation") && document.getElementById("cuponType")) {
        alert('both items have loaded.');
    }
John Hartsock
+3  A: 

There is no point in what you're trying to do. document.write happens as soon as the code is encountered, so on the next line after document.write, the text has already been added into the document.

Jani Hartikainen
A: 

You could just write:

function loadFields() {
  var load1 = document.write("<input type='text' name='StoreLocation' value='"+
    storeLocation+"' />");
  var load2 = document.write("<input type='text' name='couponType' value='"+
    couponType+"' />");
  alert('both items have loaded.');
}
loadFields();

Since as @Jani points out, the code will just be executed in the order it's given. You don't even need a function. And as John points out... your code isn't working because your function loadFields wasn't returning a value - true or false.

Rudu
A: 

The document.write calls are not asynchronous, meaning that they have taken place when any code after them are executed.

// It has not happen yet as of this point.
var load1 = document.write("<input type='text' name='StoreLocation' value='"+storeLocation+"' />");
var load2 = document.write("<input type='text' name='couponType' value='"+couponType+"' />");
// Now it has happen, as of this point.
Frank