Autofill username and password using queryselector by id - javascript

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

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.

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.

Related

trouble with storage with prompt

i need when i click on input then must prompt and result transferred to storage, help me please, i tried to find this resolve in google but no use:(
const output = document.querySelector('[data-output]');
const LOCAL_STORAGE_LIST_KEY = 'task.lists';
const LOCAL_STORAGE_SELECTED_LIST_ID_KEY = 'task.selectedListId';
let lists = JSON.parse(localStorage.getItem(LOCAL_STORAGE_LIST_KEY)) || [];
let selectedListId = localStorage.getItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY);
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(txt);
saveAndRender();
});
Your error seems to be in the renderLists function, which is on the JSFiddle that you linked in the comments. You're looping over your lists Array, which contains the input String - But you're trying to access properties as if it was an Object; which is instead giving you undefined
You have createListwhich will turn that input into an Object with the current keys, so I assume you meant to include that
output.addEventListener('click', e => {
let txt = prompt('Enter what you want to do ^^').toString();
lists.push(createList(txt));
saveAndRender();
});
Here is an updated JSFiddle

Want JS to continue if ID (document.getElementById) isn't found

I'm trying to make a javascript just "ignore" a missing div-id and keep running down the lines. Been searching for solutions, but most of them are either replacing the missing ID or putting information into an already existing one. I just want my script to be "okay" with the fact that certain ID's will not be found.
var Info01 = `Some text`;
document.getElementById("Info01").innerHTML = Info01;
var Info02 = `Some other text`;
document.getElementById("Info02").innerHTML = Info02;
If the div-id "Info01" isn't present, I want it to just be cool with that and do the next line and so on.
I've been trying some if-statements, but I'm just not good enough to figure it out by myself and google isn't providing me with the solution I'm looking for.
Hopefully someone can help!
Going a bit further with Zachary McGee's answer. You could avoid some repetition (and fetching twice the id within DOM):
const info01 = "Some text"
const info02 = "Some other text";
const setText = (id, content) => {
const item = document.getElementById(id)
if (item === null) return
item.innerText = content
}
setText("Info01", info01)
setText("Info02", info02)
<div id="Info02"></div>
Also not that I am using .innerText rather than .innerHTML, since the former is sufficient for the needs of your question and the latter is subject to XSS.
Try something like this:
Check if the element with that ID exists first.
var Info01 = "Some text";
if(document.getElementById("Info01")) {
document.getElementById("Info01").innerHTML = Info01;
}
var Info02 = "Some other text";
if(document.getElementById("Info02")) {
document.getElementById("Info02").innerHTML = Info02;
}

Display the results of an array on another page

I'm trying to load an array from one page and then have the results appear on another using javascript/jQuery. So a user will make a selection from a dropdown. Based on this dropdown the "customers" address, phone, email, etc. will appear in a text field. I'm trying to store those results in to the array (name | address | etc in one index of the array), display the result on the second screen, and then allow the user to add more names if necessary.
At the moment I'm trying to use localStorage to store the values and then JSON.stringify to convert the results so they can be stored in the array.
I think these are all of the pertinent lines:
var customerArray = [];
var getName = $('#DropDownList1').val();
var getAddress = $('#DataList1').text().trim();
var getPhone = $('#DataList2').text().trim();
var getEmail = $('#DataList3').text().trim();
//store the variables
localStorage.setItem("name", getName);
localStorage.setItem("address", getAddress);
localStorage.setItem("phone", getPhone);
localStorage.setItem("email", getEmail);
//user will click #btnAdd to add the customers information
//into customerArray[]
$("#btnAdd").click(function () {
var setName = localStorage.getItem("name");
var setAddress = localStorage.getItem("address");
var setPhone = localStorage.getItem("phone");
var setEmail = localStorage.getItem("email");
var post = setName + setAddress + setPhone + setEmail;
if (customerArray.length == 0) {
customerArray[0] = post;
} else {
for (var i = 1; i < customerArray.length; ++i) {
//store results of 'post' into the array
customerArray.push(post);
localStorage.setItem("storedArray",JSON.stringify(customerArray));
}
}
}); //end #btnAdd click event
Form here the 2nd page will load with a text field that will (should) display the results of the array (customerArray). Unfortunately I can only get 1 value to appear.
At the moment this is the block being used to display the results:
$('#tbContactList').val(JSON.parse(localStorage.getItem("storedArray")));
If it matters I'm writing the application using Visual Studio Express 2012 for Web. The data that initially populates the customers information comes from a database that I've used ASP controls to get. I'm confident there is a perfectly simple solution using ASP/C# but I'm trying to solve this problem using javascript/jQuery - I'm more familiar with those languages than I am with C#.
Thank you.
Use Array.join() to turn your array into a string to store.
Then use Array.split() to turn your string back into an Array.
Example
var arr=['name','email','other'];
var localStorageString=arr.join(',');
localStorage.setItem('info',localStorageString);
var reassemble=localStorage.info.split(',');
for(var i=0;i<reassemble.length;i++){
document.body.innerHTML+=reassemble[i]+"<br/>";
}
http://jsfiddle.net/s5onLxd3/
Why does the user have to leave the current page though? IS a tabbed/dynamic interface not an option?

JS merge duplicates in array into "[num]x string"

I'm sure that this already has a duplicate, but I couldn't find one because I had no idea on how to phrase this question. Basically, I have a JS array. The user can add items to it from a dropdown menu. This array is then fed into a textarea. The user can input the same value more than once. If they have two of the same string in the array, I would like to delete both and replace it with '2x string'. Also, if '2x string' and 'string' both exist, then they will be made into '3x string', etc, etc. Thanks in advance for answering. I really appreciate it. I tried to keep it as general as possible so that others with the same problem can get help from this too.
JS:
var newfish = 'foo';
var oldtextareacontent = 'foo';
var fish = new Array();
var fishformatted = new Array();
function addfish(){
//form is never submitted so as not to refresh page
oldtextareacontent = document.getElementById("stock").value;
newfish = document.getElementById("fish").options[document.getElementById("fish").selectedIndex].text;
fish.push(newfish);
fishformatted = fish.join("\n");
document.getElementById("stock").innerHTML = "Your stock:
" + fishormatted;
}

Receiving the data from a form to a table which is already created

I tried to receive the data from a form to another using the following code it worked.
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
Now i want to receive the data from form to a table which is already created.
I used the code as
$("table").html("<tr><td>"+fname +"</td><td>"); its not working.
In this statement,
var fname = document.getElementsByName("fname");
fname.innerHTML = "fname";
What is the element with name "fname"?
If its a form element like textbox then it should be like,
var fname = document.getElementsByName("fname");
fname.value = "fname";
your code will only work if the element is not a form element like p or div, etc tags.
Edited Code:
I hope your second page is student.html and you have written the receiveData() in this page. Then you need to read the url and set the parameter value to the element. Like the one am writing below, provided your wrote the same name in form 2 as in form1,
var fname = document.getElementsByName("fname")[0];
fname.value = getUrlVars()["fname"];
2ndly yo can do this for textbox, but for the radio and dropdown you need to write som if-else statement.
Refer this http://papermashup.com/read-url-get-variables-withjavascript/
Hope you are getting what am willing to say.
Re-Edited Code:
Add this function with the receiveData() function.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
Code for Radio Button,
var sex = document.getElementsByName("sex");
sexValue = getUrlVars()["sex"];
for(i=0;i<sex.length;i++)
{
if(sex[i].value==sexValue)
{
sex[i].checked=true;
break;
}
}
Two issues with the code.
This is a useless statement, you need to save the result to some variable (not to mention Nmae):
document.getElementsByNmae("lname")
Should be:
var lname = document.getElementsByName("lname");
And then (setinnerHTML -> innerHTML):
lname.innerHTML="lname";
Use docs not your own imagination:
var newEl = document.getElementById("newElDay");
newEl.innerHTML = document.getElementById("oldElDay").innerHTML;
Apart from other problems which people have mentioned, perhaps you are missing this as the last line of your Javascript code inside Receivedata() :
document.getElementById('myform').submit();

Categories

Resources