I have javascript code and got an error Cannot read property 'replace' of undefined. Can anyone please help me to solve this? This is my code, and I currently using jQuery 2.1.3.
ExpandableTable.prototype.updateInputBoxName=function(){
$("."+this.cloneClass,this.target).each(function(j,t){
var n=j+1;
$("input,textarea",$(t)).each(function(i,v){
if($(v).attr("name")!=""){
var newName=$(v).attr("name").replace(/\d+$/,"")+n;
$(v).attr("name",newName);
}
});
});
return this
};
ExpandableTable.prototype.updateInputBoxId=function(){
var t=this;
$("."+t.cloneClass,this.target).each(function(j,u){
var n=j+1;
$("input,textarea",$(u)).each(function(i,v){
if($(v).attr("id")!=""){
var newId=$(v).attr("id").replace(/\d+$/,"")+n;
$(v).removeAttr("id").attr("id",newId);
}
});
});
return this
};
it says i have an error on .replace.
Please help me to solve this
I have javascript code and got an error Cannot read property 'replace' of undefined. Can anyone please help me to solve this? This is my code, and I currently using jQuery 2.1.3.
ExpandableTable.prototype.updateInputBoxName=function(){
$("."+this.cloneClass,this.target).each(function(j,t){
var n=j+1;
$("input,textarea",$(t)).each(function(i,v){
if($(v).attr("name")!=""){
var newName=$(v).attr("name").replace(/\d+$/,"")+n;
$(v).attr("name",newName);
}
});
});
return this
};
ExpandableTable.prototype.updateInputBoxId=function(){
var t=this;
$("."+t.cloneClass,this.target).each(function(j,u){
var n=j+1;
$("input,textarea",$(u)).each(function(i,v){
if($(v).attr("id")!=""){
var newId=$(v).attr("id").replace(/\d+$/,"")+n;
$(v).removeAttr("id").attr("id",newId);
}
});
});
return this
};
it says i have an error on .replace.
Please help me to solve this
Share Improve this question asked Jan 4, 2016 at 3:29 Ridho FauzanRidho Fauzan 1631 gold badge3 silver badges10 bronze badges 3-
Use the debugger to figure out what is
undefined
and why. – SLaks Commented Jan 4, 2016 at 3:30 - As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. – MinusFour Commented Jan 4, 2016 at 3:32
-
if($(v).attr("id")!=""){
does not test for undefined. – 001 Commented Jan 4, 2016 at 3:35
1 Answer
Reset to default 3Your if statement needs to check that $(v).attr("id")
is not undefined
if ($(v).attr("id") != "" && typeof $(v).attr("id") != 'undefined') {
Should stop that error.
As MinusFour said if ($(v).attr("id"))
is less verbose and achieves the same thing.