admin 管理员组文章数量: 1086019
I'm trying to submit a form of a specific element in my webpage but i get a
Uncaught TypeError: Cannot read property 'form' of undefined
This is the JavaScript script for my webpage
<script type="text/javascript">
var aTags = document.getElementsByName("s");
for (var i=0;i<aTags.length;i++){
aTags[i].addEventListener('click', function(e){
e.preventDefault();
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if(result){
aTags[i].form.submit();
}
}
});
});
}
</script>
I'm trying to submit a form of a specific element in my webpage but i get a
Uncaught TypeError: Cannot read property 'form' of undefined
This is the JavaScript script for my webpage
<script type="text/javascript">
var aTags = document.getElementsByName("s");
for (var i=0;i<aTags.length;i++){
aTags[i].addEventListener('click', function(e){
e.preventDefault();
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if(result){
aTags[i].form.submit();
}
}
});
});
}
</script>
Share
Improve this question
edited May 1, 2019 at 0:25
Amine
asked May 1, 2019 at 0:20
AmineAmine
9713 gold badges16 silver badges38 bronze badges
4
-
The error means that
aTags[i]
isundefined
. Usually submitting multiple forms like that doesn't make a lot of sense. – Pointy Commented May 1, 2019 at 0:23 - i updated the original post – Amine Commented May 1, 2019 at 0:26
-
What is
.form
? Is it a<form>
tag? Synthetically it looks like is a property of an HTMLCollection (which actually doesn't exist unless it's from bootbox) – zer00ne Commented May 1, 2019 at 0:38 - Yeah it's a <form> tag which retrieves the form element of a certain element – Amine Commented May 2, 2019 at 22:51
1 Answer
Reset to default 4Every one of the click handlers is referencing the exact same i
variable. By the time the button is clicked, i
has long ago been incremented to aTags.length
. So aTags[i]
resolves to aTags[aTags.length]
, which is undefined.
Simplest solution is to just use let
instead of var
. That way, every time through the loop gets a new binding of the variable, and thus the click handlers are all associated with the correct value.
for (let i = 0; i < aTags.length; i++){
// rest of the code the same
}
本文标签: htmlHow to fix Uncaught TypeError in JavaScriptStack Overflow
版权声明:本文标题:html - How to fix Uncaught TypeError in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744072364a2528722.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论