JavaScript: Can't set value to textarea with custom class on the first load

Discussão em 'Angular' iniciado por Diego Cast, Novembro 13, 2024.

  1. Diego Cast

    Diego Cast Guest

    Question: I am trying to programmatically set a value inside a textarea with the following code:


    function setTextareaValue(textareaId, value) {
    // Recursive function to wait until the element is available
    function waitForTextarea() {
    const textareaElement = document.getElementById(textareaId);
    if (textareaElement && textareaElement.querySelector('.hwt-input')) {
    // Once the element is available, set the value
    const textareaInput = textareaElement.querySelector('.hwt-input');
    textareaInput.value = value;
    textareaInput.dispatchEvent(new Event("input", { bubbles: true }));
    textareaInput.dispatchEvent(new Event("change", { bubbles: true }));
    } else {
    // If the element is not available, try again after 100ms
    setTimeout(waitForTextarea, 100);
    }
    }

    // Start the recursive function
    waitForTextarea();
    }

    // Use the function to set the value to the textarea
    setTextareaValue('MarcEditorPresenter.textArea.050.Left.6', 'Value set by code');

    However, this doesn’t work the first time I open the form. If I manually click and type in the field, then run the script again, it still doesn’t work. It only works when I open the "Inspect" tool, click on the textarea code in the inspector, and then the value is set correctly.

    I've tried debugging, simulating the textarea activation in code, but it still doesn’t work. Any ideas on why this might happen and how to solve it?

    [​IMG]

    Continue reading...

Compartilhe esta Página