У меня есть модал. В зависимости от установленного значения переменной контекста модал будет отображать одну из трех html групп. Его три модальности в одном.
Модал заполняет различные значения html через объект json:
var object = [
{
id: 34,
week: '9/15/20',
suggestednumber: 6,
number: null
},
{
id: 674,
week: '10/13/20',
suggestednumber: 70,
number: null
},
{
id: 54,
week: '11/17/20',
suggestednumber: 34,
number: null
}
];
Две кнопки и форма будут заполняться в активном контексте для каждого объекта json в массиве. Форма будет предварительно заполнена предлагаемым значением номера.
/* function that populates the buttons and form fields of the selected modal
takes the css id of the row its populating.
*/
function populate(cssid){
/* script for forcasted deplitions tested for loop */
for( i = 0; i < object.length; i++){
$(cssid).append("<div class=\"col-xs-12\">\n" +
` <p class=\"text-left text-uppercase text-muted\">wk of ${object[i].week}</p>\n` +
" </div>\n" +
" <div class=\"col-xs-4 m-0 p-0\">\n" +
` <button onclick=\"cbibuttonclick(${object[i].id})\" class=\"btn btn-default btn-block m-0 p-0\">` +
`<span id=\"${object[i].id}\" class=\"text-uppercase text-primary cbi\">cbi</span></button>\n` +
" </div>\n" +
" <div class=\"col-xs-4 m-0 p-0\">\n" +
` <button onclick=\"custombuttonclick(${object[i].id})\" class=\"btn btn-default btn-block m-0 p-0\"><span id=\"${object[i].id}\" class=\"text-uppercase text-muted custom\">custom</span></button>\n` +
" </div>\n" +
" <div class=\"col-xs-4\">\n" +
" <form class=\"form-inline\">\n" +
" <input type=\"number\"\n" +
` onclick=\"formclick(${object[i].id})\"\n` +
` onchange=\"update(${object[i].id})\"\n` +
" class=\"form-control finput\"\n" +
` id=\"${object[i].id}\">\n` +
" </form>\n" +
" </div>");
console.log('this is the iterator for the form creation');
console.log(i);
document.getElementsByClassName('finput')[i].value = object[i].suggestednumber;
}
}
У меня проблема с последней строкой вышеуказанной функции:
document.getElementsByClassName('finput')[i].value = object[i].suggestednumber;
при запуске я получаю следующую ошибку:
jQuery.Deferred exception: Cannot set property 'value' of undefined TypeError: Cannot set property 'value' of undefined
at populate (file:///Users/christopher.jakob/Documents/softwareprojects/slalom/constellationBrands/modalsublime.html:91:60)
at HTMLDocument.<anonymous> (file:///Users/christopher.jakob/Documents/softwareprojects/slalom/constellationBrands/modalsublime.html:40:9)
at e (https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js:2:29453)
at t (https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js:2:29755) undefined
k.Deferred.exceptionHook @ jquery.min.js:2
t @ jquery.min.js:2
setTimeout (async)
(anonymous) @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
fire @ jquery.min.js:2
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
ready @ jquery.min.js:2
B @ jquery.min.js:2
jquery.min.js:2 Uncaught TypeError: Cannot set property 'value' of undefined
at populate (modalsublime.html:91)
at HTMLDocument.<anonymous> (modalsublime.html:40)
at e (jquery.min.js:2)
at t (jquery.min.js:2)
document.getElementsByClassName('finput')[i].value = object[i].suggestednumber;
Теперь интересно, когда я удаляю [i]
рядом с ('finput
)из приведенного выше кода: мой код не ломается, однако на экране нет кнопок.
Всем понятно, в чем может быть проблема?
для хихиканья Я поместил обновление значения формы в свой собственный цикл for, который будет выполняться после того, как весь html-код добавлен jquery. Но ошибка все еще сохранялась
// for loop to populate form inputs as it seems trying to do so in one for loop make the thing unhappy
for(i =0; i< object.length; i++){
x = document.getElementsByClassName('finput')[i].value = object[i].suggestednumber;
}
Когда я консольный журнал, вызов jquery класса find элемент я получаю это
here is the result of attempting to find the form class
modalsublime.html:92
HTMLCollection []
length: 0
__proto__: HTMLCollection
item: ƒ item()
arguments: (...)
caller: (...)
length: 1
name: "item"
__proto__: ƒ ()
apply: ƒ apply()
arguments: (...)
bind: ƒ bind()
call: ƒ call()
caller: (...)
constructor: ƒ Function()
length: 0
name: ""
toString: ƒ toString()
Symbol(Symbol.hasInstance): ƒ [Symbol.hasInstance]()
get arguments: ƒ ()
set arguments: ƒ ()
get caller: ƒ ()
set caller: ƒ ()
__proto__: Object
[[FunctionLocation]]: <unknown>
[[Scopes]]: Scopes[0]
[[Scopes]]: Scopes[0]
No properties
length: (...)
namedItem: ƒ namedItem()
arguments: (...)
caller: (...)
length: 1
name: "namedItem"
__proto__: ƒ ()
[[Scopes]]: Scopes[0]
No properties
constructor: ƒ HTMLCollection()
Symbol(Symbol.iterator): ƒ values()
Symbol(Symbol.toStringTag): "HTMLCollection"
get length: ƒ length()
__proto__: Object