Reputation: 2521
I have a dynamically created multiple textAreas in javascript through loop. I made it "readonly" and set different values using string now i want that whenever click on any textArea a function should be call.Now in this function i want to show the value of clicked textarea. Now for that i need clicked textarea's id. I get it through textarea.id but it shows me the last id of the dynamically created textareas. Like if i have created 15 textareas then on getting id it shows me 15th id.
var div = document.createElement("div");
div.setAttribute("style","margin-left:10px;width:750px;height:180px;background-image:url(images/questions_option_bg_2.png);position:relative;margin-top:15px");
textarea = document.createElement("textarea");
textarea.setAttribute('id', "textid"+i);
textarea.setAttribute('readonly', 'readonly');
textarea.setAttribute("cols",35);
textarea.setAttribute("rows",5);
textarea.setAttribute("style","overflow:hidden;color: white; font-size: 30px;margin-left:10px;position:relative;margin-top:5px;background:transparent;border:thin;outline:none;");
textarea.value=all_sel_questions[(question_shuffled_array[i])];
div.appendChild(textarea);
$("#third_div").append(div);
textarea.addEventListener('click', clickonTextArea, false);
function clickonTextArea()
{
var value=textarea.id;
alert(value);
}
Upvotes: 0
Views: 542
Reputation: 55740
Use this
context
function clickonTextArea(e) {
var value=this.id;
// OR
// var value = e.target.id;
alert(value);
}
The textarea
holds reference to the last textarea that you have bound to . So it always points to the last instance of the one that you have created.
Upvotes: 1
Reputation: 34895
You can access the target text area through this
in the event handler.
function clickonTextArea(event) {
var value = this.id;
alert(value);
}
Upvotes: 1
Reputation: 12305
Your event function should be like this...
function clickonTextArea(e)
{
var e = e || window.event;
var ta = e.target || e.srcElement;
var value=ta.id;
alert(value);
}
Upvotes: 0