Add onclick property to input with JavaScript

101,302

Solution 1

Try this:

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

Steve

Solution 2

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?

Solution 3

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...

Solution 4

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');
Share:
101,302
S. Plekhanov
Author by

S. Plekhanov

Updated on July 19, 2022

Comments

  • S. Plekhanov
    S. Plekhanov almost 2 years

    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?

  • S. Plekhanov
    S. Plekhanov about 15 years
    Tried it, but the input didn't get the onclick property. What might be going on there?
  • S. Plekhanov
    S. Plekhanov about 15 years
    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.
  • Steve Harrison
    Steve Harrison about 15 years
    How are you determining whether the input got the "onclick" function or not?
  • Steve Harrison
    Steve Harrison about 15 years
    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?