Yukino
Yukino

Reputation: 57

How to trigger change event when set input element value with js

I want to write a chrome extension which can auto fill password. The code is like:

//get the account
document.querySelector("input[type=text]").addEventListener('input', () => {
    fillPassword();
})

function fillPassword() {
    let password = '';
    // some operation to get password
    document.querySelector("input[type=password]").value = password
}

Everything works well, the password has been got and 'setted' correctly, expect login. When I click Login button, it notice me 'password can not be empty'. So this is my idea.

Because the website is written by vue, the change event is not trigged, the password is not set in the login form. So my problem now is how to trigger the change event of input so that let its value can be trapped by vue rightly.

I tried to validate my idea, so I add a listener to the password input.

//get the account
document.querySelector("input[type=text]").addEventListener('input', () => {
    fillPassword();
})

document.querySelector("input[type=password]").addEventListener('change', () => {
    console.log('changed')
})

function fillPassword() {
    let password = '';
    // some operation to get password
    document.querySelector("input[type=password]").value = password
}

And there is no print as expect. Then I try to trigger the change event, but it seems no work.

const e = new Event("change");
const element = document.querySelector("input[type=password]")
element.value = password;
element.dispatchEvent(e);

Upvotes: 2

Views: 6820

Answers (1)

Yukino
Yukino

Reputation: 57

Oh, I fix it. The change event did triggered, but v-model listen input is input event. So I change change event to input, then it works well.

Upvotes: 2

Related Questions