Autofill username and password using queryselector by id

1.8k Views Asked by At

I’m trying to create some simple javascript to autofill a webpage.

I’d like to modify the following for use with a specific elementid for the username ‘password_username’ and password ‘password_password’

var result = [];

// Get all links from the page need to change to specific for username

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "username";
}

// Get all links from the page need to change to specific for password

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "password";
}

// Call completion to finish
completion(result) `

I’ve only just started to learn code and have very basic javascript knowledge, any help is appreciated!

Cheers,

Mat

2

There are 2 best solutions below

5
Petar On BEST ANSWER

Not entirely sure if this will work as imagined as I can't test it out right now, but give it a shot:

const usernameElements = document.querySelectorAll(`input[type="text"]`);
const passwordElements = document.querySelectorAll(`input[type="password"]`);

usernameElements.forEach(username => username.value = "the user name");
passwordElements.forEach(password => password.value = "the password");

It selects the input fields according to the type (text/password) and adds the value to them. Now I am not entirely sure if this that you posted is part of a bigger script, but this might do the trick that you need. You'd need to make the username and password variables to dynamically load, if you want different usernames and passwords, otherwise this adds the values that you give it, like for example username.value = "testing username" and password.value = "testing password" . Cheers.

1
Nikita Skrebets On

Hope I understood your question correctly.

To select a specific field by id and set a value to it, you may use document.querySelector("#the_id").value = "the_value";

If you have an object with {id: value} structure, you can process it in a loop:

const creds = {
  id1: 'val1',
  id2: 'val2' // ...
};

for (const [id, val] of Object.entries(creds)) {
  document.querySelector(`#${id}`).value = val;
}

Please clarify if I did not understand what you need, I'll be glad to help.