Isaias
Isaias

Reputation: 347

Adding a button with innerHTML property

I'm trying to add html code inside a <span id="options"></span> so I'm trying to use this:

function editTextArea(element) {
   var options = document.getElementById("options");
   options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea('" + element.id + "')' >Add</button><br>";
}

But this is what I got,

<button type="button" onclick="updateTextArea(" textarea0')'="">Agregar</button>

My problem is with the quotes, so I later tried using createElement("button"), but now I can't add the onclick attribute.

I'm not using jQuery, so it would be nice to have a solution without it.

Upvotes: 4

Views: 55192

Answers (3)

user732456
user732456

Reputation: 2688

Can be done with escaping the quotes also:

options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick=\"updateTextArea(\'" + id + "\')\" >Add</button><br>";

Upvotes: 1

Punit
Punit

Reputation: 1120

if you are going with second option you can use setAttribute() method.

var ele = document.createElement('button');
ele.setAttribute('onclick','method_name');

Upvotes: 0

GoldenNewby
GoldenNewby

Reputation: 4452

You need to use different quotes for the function call to updateTextArea than you do for the onclick attribute. You can't do onclick='alert('hi');', because the single quote terminates the onclick attribute.

function editTextArea(element) {
   var options = document.getElementById("options");
   options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea(" + '"' + + element.id + '"' + ")' >Add</button><br>";
}

You should definately consider doing this at least with the proper DOM API calls. You are right to try document.createElement

To set an onclick, do something like this:

var button = document.createElement('button').
button.onclick = function(){
 alert('I was clicked');
}

Upvotes: 6

Related Questions