Add onclick property for input using JavaScript

I create user input in 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 result does not have the onclick property. I tried to use

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

... instead, but did not work. What am I doing wrong?

+17
javascript input onclick
Apr 25 '09 at 10:15
source share
4 answers

Try the following:

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

Steve

+30
Apr 25 '09 at 22:20
source share

There is a problem here with one of your lines; I fixed 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); } 

It makes sense?

+6
Apr 25 '09 at 22:28
source share

I think you might need to avoid \ r \ n if you intend to pass these ...

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

I don’t quite understand what your onclick handler is aiming for ...

+2
Apr 25 '09 at 22:21
source share

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

  $('<input type="submit" value="Join chat" />') .click( function() { conn.send('$connect\r\n'); } ) .appendTo('<div></div>') .appendTo('#box'); 
+1
Apr 25 '09 at 22:59
source share



All Articles