Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
Isaias Avatar asked Oct 22 '25 06:10

Isaias


2 Answers

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');
}
like image 191
GoldenNewby Avatar answered Oct 23 '25 20:10

GoldenNewby


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>";
like image 40
user732456 Avatar answered Oct 23 '25 21:10

user732456



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!