views:

3369

answers:

4

I am creating a user input at one of the events:

var throwConnectBox = function() {
    chat_box = document.getElementById('box');
    div = window.parent.document.createElement('div');
    input = window.parent.document.createElement('input');
    input.type = "submit";
    input.value = "Join chat";
    input.onclick = "conn.send('$connect\r\n');";
    div.appendChild(input);
    chat_box.appendChild(div);
}

... but the resulting input does not have onclick property. I tried to use

    input.onclick = conn.send('$connect\r\n');

... instead, but didn' work either. What am I doing wrong?

+2  A: 

Try this:

 input.onclick = function() { conn.send('$connect\r\n'); };

Steve

Steve Harrison
aaaahhhh that's well spotted :)
Peter Perháč
Tried it, but the input didn't get the onclick property. What might be going on there?
Alex
How are you determining whether the input got the "onclick" function or not?
Steve Harrison
I go to FireBug and look in the "HTML" section if it has it.
Alex
Interesting. I quickly tried creating an element with an "onclick" handler and adding it to the DOM, and it didn't show up in the HTML section (but the onclick handler was there and working). Try adding an ID attribute to the input (let's assume the ID is "test"), and execute the following code (without the single quotes) in Firebug's console: 'document.getElementById("test").onclick'. Do you get back a function?
Steve Harrison
Yeah :) It worked.
Alex
+1  A: 

I think you may want to escape the \r\n, if you intend to pass these...

conn.send('$connect\\r\\n')

I don't quite see what your onclick handler tries to achieve...

Peter Perháč
Ah, no problem with that, it works fine (it sends a line via a TCP socket). I'm actually stuck with attaching the onclick property to the input tag.
Alex
A: 

There is a problem with one of your lines here; I've corrected it for you:

 var throwConnectBox = function() {
     chat_box = document.getElementById('box');
     div = window.parent.document.createElement('div');
     input = window.parent.document.createElement('input');
     input.type = "submit";
     input.value = "Join chat";
     /* this line is incorrect, surely you don't want to create a string? */
     // input.onclick = "conn.send('$connect\r\n');";?
     input.onclick = function() { 
         conn.send('$connect\r\n'); 
     };
     div.appendChild(input);
     chat_box.appendChild(div);
 }

Does that make more sense?

Ben
That's what it was, thanks.
Alex
+1  A: 

This is one of the reasons why I've decided to use jQuery:

 $('<input type="submit" value="Join chat" />')
      .click( function() { conn.send('$connect\r\n'); } )
      .appendTo('<div></div>')
      .appendTo('#box');
tvanfosson