how do I pass a variable to a function that is attached to an event handler and also prevent default in javascript?

Viewed 26

I am writing a function for autofill, which will display a list of values to select as potential value input. The names of the input fields are dynamic so I need to pass that to the function that is executed by the event handler, but I also need to prevent default button action. The error that I've been getting is that the passed targetField gets seen as the event and I have not been able to figure out how to fix this. Would appreciate some help. This is what I have now.

function dropdownList(testlist, clicked) {

    const listEl = document.createElement("ul");
    listEl.classname = "autocomplete-list";


    testlist.forEach(item => {
        const listItem = document.createElement("li");

        const valueButton = document.createElement("button");
        valueButton.innerHTML = item
        valueButton.addEventListener("click", valueSelect(targetField);
        listItem.appendChild(valueButton);

        listEl.appendChild(listItem)
    })

    let clickedId = `scripts-${clicked}-script`
    let targetField = document.querySelector("[data-testid=" + clickedId + "]")
    document.querySelector("[data-testid=" + clickedId + "]").after(listEl)
    
    valueSelect(targetField);
}


function valueSelect(targetField) {
    event.preventDefault();
    const buttonEl = event.target;

    targetField.value = buttonEl.innerHTML

}
1 Answers

This code works. Your problem was mostly with the eventListener, and with the parameters of the valueSelect function.
Note: I changed your clicked variable to be the actual element, not the element's id

document.querySelector("#myInput").addEventListener("click", (event)=>dropdownList(["a", "b", "c"], event.target))

function dropdownList(testlist, clicked) {

    const listEl = document.createElement("ul");
    listEl.classname = "autocomplete-list";


    testlist.forEach(item => {
        const listItem = document.createElement("li");

        const valueButton = document.createElement("button");
        valueButton.innerHTML = item
        valueButton.addEventListener("click", (event)=>valueSelect(event, clicked));
        listItem.appendChild(valueButton);

        listEl.appendChild(listItem)
    })

    clicked.after(listEl)
}


function valueSelect(event, targetField) {
    event.preventDefault();
    const buttonEl = event.target;

    targetField.value = buttonEl.innerHTML

}
<label>Test</label><input type="text" id="myInput" />

Related