How to solve error TypeError: Cannot set property list of #<HTMLInputElement> which has only a getter?

Viewed 553

I am new to javascript trying to build a file upload where users can upload a file or select a file from a dropdown or enter a file path.

Everything is working fine until I tried to create a list 'car' to provide two example select options inside the input element.

FileUpLoad (input_def) {

input_def.id = this.uid()

const Label = document.createElement('label')
Label.className = 'custom_file_upload'
const Input = document.createElement('input')
Input.type = 'file'

const Input1 = document.createElement('input')
Input1.type = 'text'
Input1.list = 'car'

const DataList = document.createElement('datalist')
DataList.id = 'car'

const Option1 = document.createElement('option')
Option1.textContent = 'Volvo'
DataList.append(Option1)

const Option2 = document.createElement('option')
Option2.textContent = 'Suzuki'
DataList.append(Option2)

Label.append(Input)
Label.append(Input1)
Label.append(DataList)
const Li = document.createElement('i')
Li.innerText = ' Upload Data'
Li.className = "fa fa-cloud-upload"
Label.append(Li)

const row = document.createElement('div')
row.className = 'ui-form-element section-row'
row.id = input_def.id

row.append(Label)
return row

}

How to solve this error?

TypeError: Cannot set property list of #<HTMLInputElement> which has only a getter

I was trying to follow this solution.

HTML select form with option to enter custom value

thanks

2 Answers

That's because the "list" attribute is read-only and therefore you need to use the setAttribute function to set it/change it.

Try this:

const Input1 = document.createElement('input')
Input1.type = 'text'
Input1.setAttribute("list","car")

Replace Input1.list = 'car' with the below line, because list attribute is read-only and actually returns a reference to a DOM element, you need to use setAttribute to set the list property.

Input1.setAttribute('list', 'cars');
Related