I want to access the javascript object property with a keyword in it:
var cloneIndex = $(".clonedInput").length + 1; $(document).on("click", 'button.clone', function (e) { e.preventDefault(); $(this).closest(".clonedInput").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + cloneIndex).find("[id], [name] ,[data-valmsg-for]").each( function () { this.id = this.id.replace(/\d+$/, cloneIndex); this.name = this.name.replace(/\d/, cloneIndex); this.data-valmsg-for = this.data-valmsg-for.replace(/\d/, cloneIndex); }); cloneIndex++; }); But because of the line:
this.data-valmsg-for = this.data-valmsg-for.replace(/\d/, cloneIndex); That has:
this.data-valmsg-for It throws an error because "for" in data-valmsg-for is a keyword. Also when I changed:
this.data-valmsg-for To:
this['data-valmsg-for'] = this['data-valmsg-for'].replace(/\d/, cloneIndex); Script throws this error:
Uncaught TypeError: Cannot read property 'replace' of undefined Also when I changed:
this.data-valmsg-for To:
this.setAttribute('data-valmsg-for',this.getAttribute('data-valmsg-for').replace(/\d/, cloneIndex)); Script throws this error:
Uncaught TypeError: Cannot read property 'replace' of null And this is my html:
<div id="clonedInput1" class="form-group clonedInput"> <input id="CompanyId1" name="[0].CompanyId" type="hidden" value=""> <label class="control-label col-md-2" for="NationalCode">کد ملی</label> <div class="col-md-3"> <input class="form-control text-box single-line" data-val="true" data-val-regex="فرمت کد ملی صحیح نمی باشد" data-val-regex-pattern="^[0-9]{10}$" @*data-val-remote="'کد ملی' is invalid." data-val-remote-additionalfields="*.NationalCode,*.initialNationalCode" data-val-remote-url="/Account/IsValidNationalCode"*@ data-val-required="وارد کردن کد ملی اجباریست" id="NationalCode1" name="[0].NationalCode" type="text" value=""> <span class="field-validation-valid text-danger" data-valmsg-for="[0].NationalCode" data-valmsg-replace="true"></span> </div> <label class="control-label col-md-2" for="BirthDate">BirthDate</label> <div class="col-md-3"> <input class="form-control text-box single-line" data-val="true" data-val-date="The field BirthDate must be a date." data-val-required="The BirthDate field is required." id="BirthDate1" name="[0].BirthDate" type="date" value=""> <span class="field-validation-valid text-danger" data-valmsg-for="[0].BirthDate" data-valmsg-replace="true"></span> </div> </div>
[ ]notation, and you have to check to see whether the properties exist.for. The problem is primarily the-.this.data-valmsg-formeansthis.dataminusvalmsgminusfor. "Cannot read property 'replace' of undefined" means that the property doesn't exist. If the property was justfor, thenthis.forwould work perfectly fine.thisis a DOM element, you are looking forthis.getAttribute('data-valmsg-for').