Reputation: 73241
I have this function:
var save = document.getElementById('savethis'+this.parentNode.childNodes[1].id);
save.addEventListener('click', savethis.bind(this), false);
function savethis() {
this.removeEventListener('click', edit);
var a = this.childNodes[0].childNodes[0].id;
console.log(a);
var b = document.getElementById(a);
console.log(document.getElementById(a).id.replace('minedit',''));
console.log(b.value);
this.innerHTML = b.value;
this.parentNode.cells[4].className = 'text-center min-edit';
setTimeout(function() {this.addEventListener('click',edit);},1);
}
In another function:
var minedit = document.getElementsByClassName('min-edit');
for (var m=0;m<minedit.length;m++){
minedit[m].addEventListener('click', edit);
}
function edit(){
var avalue = this.innerHTML;
console.log(avalue);
if (this.className.indexOf('input-open')>=0){
}
else {
this.className += ' input-open';
var content = '';
content += '<div class="input-group editable-input"><input type="text" id="minedit'+this.parentNode.childNodes[1].id+'" value="'+parseFloat(avalue).toFixed(2)+'" class="form-control"><span class="input-group-addon editable-input" id="savethis'+this.parentNode.childNodes[1].id+'"><i class="ion-android-done" ></i></span><span class="input-group-addon editable-input"><i class="ion-android-close" id="close"></i></span></span></div>';
this.innerHTML = content;
valuenow = document.getElementById('minedit'+this.parentNode.childNodes[1].id).value;
id = document.getElementById('minedit'+this.parentNode.childNodes[1].id).id;
var save = document.getElementById('savethis'+this.parentNode.childNodes[1].id);
save.addEventListener('click', savethis.bind(this), false);
}
}
function savethis() {
this.removeEventListener('click', edit);
var a = this.childNodes[0].childNodes[0].id;
var b = document.getElementById(a);
this.innerHTML = b.value;
this.parentNode.cells[4].className = 'text-center min-edit';
setTimeout(function() {this.addEventListener('click',edit);},1);
}
As you can see in the fiddle, the opening and closing of the input box works on the first click, but on the second click I get an error saying
TypeError: this.className is undefined
pointing to this line:
if (this.className.indexOf('input-open')>=0){
I totally don't get why className could possibly be undefined, as I define it's name within the savethis function.
Can someone explain and help?
Upvotes: 0
Views: 946
Reputation: 207501
scope is wrong
setTimeout(function() {this.addEventListener('click',edit);},1);
this
is the document when this runs, not the element.
var that = this;
setTimeout(function() {that.addEventListener('click',edit);},1);
or use bind() with modern browsers
setTimeout( (function() {this.addEventListener('click',edit);}).bind(this),1);
Upvotes: 1