views:

88

answers:

2

Ok, I am developing a simple program to do xmlhttprequests so I can get a handle on how they work. On that page I have a simple text box, a label, and a button. When the button is clicked it sends out a request to another page via the javascript method, and it stores the response in the label.

(this is all the code in the body)

<form id="form1" runat="server">
        <div>
            <input type="text" id="text1" value="StuffInTheBox" name="text1"/>
            <label id="label1">Please Enter Name.</label>
        </div>
</form>
<button id="button1" onclick="checkName(text1.value,'')">BUTTON</button>

This works perfectly in google chrome. But when it came time to try it out in IE7 it gave me an error. It said "Error: 'text1' is undefined". I've been trying to tweak everything I can to see if it makes a difference but now I'm kind of lost.

Any help would be much appreciated

edit: checkname function per request

The method calls loadXMLDoc which creates the xmlhttprequest object, forking the construction for older IE who use ActiveX and modern browers who have it native. It also creates a method to watch the status change, and if it is done successfully it recalls checkname with checkName('',results)

function checkName(input, response)
    {        
      if (response != ''){ 
        // Response mode
        message   = document.getElementById('label1');
        message.innerHTML = response;

      }else{
        // Input mode
        loadXMLDoc("http://localhost/xmlTest/Return.aspx","input="+input);
      }
    }
+6  A: 

In your JavaScript "checkName(text1.value,'')" it is unclear what text1.value is referencing. You're assuming it's referencing the DOM Object you've declared in your HTML and FireFox seems to make that assertion as well however IE doesn't. text1 could have easily been a reference to an object declared earlier in your JavaScript code.

var text1 = {value: ""};

Frankly I'm surprised that FireFox didn't throw an error.

When referring to DOM objects (i.e. HTML elements) you need to use the document.getElementById or document.getElementsByName methods.

The following example was tested and works in both FireFox and IE and I would assume to work in Chrome, Safari and Opera as well.

<form id="form1" runat="server">
        <div>
            <input type="text" id="text1" value="StuffInTheBox" name="text1"/>
            <label id="label1">Please Enter Name.</label>
        </div>
</form>
<button id="button1" onclick="checkName(document.getElementById('text1').value,'')">BUTTON</button>
CptSkippy
+2  A: 

"text1" is the id of the input, but you haven't declared that the text1 variable in the JavaScript refers to that.

Perhaps this will work for you:

<button id="button1" onclick="checkName(document.getElementById('text1').value,'')">BUTTON</button>

It uses document.getElementById to retrieve the input before trying to find its value.

Phil