Prefill form based on URL parameters javascript - javascript

I'm passing name & email through URL parameters from a popup form like this
xyz.com?om_email=test%40test.com&om_name=Test
I need these two forms prefilled on xyz.com site
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
Can anyone please help?

More context would be nice, but try this:
I used a test URL string to allow the example to work, but on the actual site, replace params variable with the one that is commented, (hint: window.location.search) to extract the parameters from the URL.
There are different ways to do this, but I created an object from the parameter string then looped over the inputs and updated their value by matching the data object key to the input value name attribute.
Note: Be sure to run the JavaScript after the page loads.
var url = "xyz.com?om_email=test%40test.com&om_name=Test";
var params = "om_email=test%40test.com&om_name=Test".split("&");
//use this on the actual site to extract parameters from the url
//var params = window.location.search.slice(1).split("&");
//convert the params to an object
var data = params.reduce((obj, param) => {
var pair = param.split("=");
return { ...obj,
[pair[0].replace("om_", "")]: decodeURIComponent(pair[1])
}
}, {});
//console.log({data});
//insert values by matching input name to data object key
document.querySelectorAll("input").forEach(input => input.value = data[input.name]);
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>

This is how to autofill a form using HTML5.
<input value="valuehere">

Related

How to append HTML form data into the URL as path and not as a query string?

So a typical HTML form with a get would look like this :
<form action="https://mywebsite.com/mypage" method="get">
<input type="text" id="myparam" name="myparam">
<input type="submit" value="Submit">
</form>
and takes the user to :
https://mywebsite.com/mypage?myparam=value
However, I would like to know if it is possible for my form to take my user to :
https://mywebsite.com/mypage/value ? Basically, adding the myparam input's value to the path at the end of the url.
Thanks in advance !
You can create javascript function or you can declare a backend function, and return a redirect to your request route
document.querySelector('form').addEventListener("submit", function (e) {
e.preventDefault()
let param = document.querySelector('input[name="myparam"]').value
window.location.href = 'https://mywebsite.com/mypage/' + param
})

Is there a way to nest an array inside of an object using the name attribute within a form?

I am building an full-stack application in where I have a form submitting data to one of my post routes. On this form, I have all of my input fields bundled into req.body.model, thanks to the fact that I can add a name attribute with square brackets around the key, like so name="model[height]".
This should equate to something like this:
model = {
height: //value,
weight: //value,
age: //value
}
However, I want one of the values to be an empty array so I can push URLS into the array, like so:
model = {
height: //value,
weight: //value,
age: //value,
urls: [//urls here]
}
Since you can automatically create an object using the name attribute, I was wondering if there was a way to create a nested array using the name attribute as well?
Code snippet
<form>
<input type="text" name="model[height]">
<input type="text" name="model[weight]">
<input type="text" name="model[age]">
// these 2 inputs would go into the urls key in the models object
<input type="text">
<input type="text">
<button>Submit</button>
</form>
Not sure if I worded this properly...but let me know if I can explain in further detail.
If you pass index next to the property you can create an array. Something like this
// these 2 inputs would go into the urls key in the models object
<input type="text" name="model[urls][0]">
<input type="text" name="model[urls][1]">
Not sure if I got what you are trying to do exactly, but it seems like you can first process the submitted data and then send the processed data to wherever you want to send it. It's a bit more verbose, but I feel like it may give you more flexibility when organising your data. So maybe you can do something like this:
html
<form name="model">
<input type="text" id="height">
<input type="text" id="weight">
<input type="text" id="age">
<input type="text" id="url1">
<input type="text" id="url2">
<button onclick="processForm()">Submit</button>
</form>
script
function processForm() {
let height = document.querySelector("#height").value;
let weight = document.querySelector("#weight").value;
let age = document.querySelector("#age").value;
let url1 = document.querySelector("#url1").value;
let url2 = document.querySelector("#url2").value;
let model = {
"height": height,
"weight": weight,
"age": age,
"url": [url1, url2]
}
// now you can send model object to where it is needed
}

How to populate an textboxes with query string value(s) from URL

I have a simple Window Forms application that opens up a webpage with set parameters.
The link send the user to a page with 2 text box fields and a submit button.
I am trying to automate this process so it grabs the parameter values and puts it into the text box then clicks submit .
This is my current code for my windows form:
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
libLink.Links.Remove(libLink.Links[0]);
libLink.Links.Add(0, libLink.Text.Length,
"http://www.example.com/?UserName=value1&FirstName=value2");
}
private void libLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
ProcessStartInfo sInfo = new ProcessStartInfo(e.Link.LinkData.ToString());
Process.Start(sInfo);
}
}
}
How can I create a script that that takes those parameters in the URL to populate two text box fields and then submit the form?
This is my HTML Page:
<form action="/send" method="post" novalidate="novalidate">
<input class="form-control" data-val="true" data-val-UserName="Wrong username" data-val-required="Enter a valid Username" id="Username" name="Username" placeholder="Username" type="text" value="">
<input class="form-control" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
<button type="submit">Sign In</button>
</form>
Fairly new to coding so I tried to keep my code as simple as possible.
I looked at possible methods such as QueryStrings, JavaScript and Jquery, but I am not sure how to approach this problem.
There's a few ways of doing it really but i'll give you a basic walk through of how i would do it in javascript with a bit of JQuery.
we have variable with the URL we start by:
var url = "http://www.example.com/?UserName=value1&FirstName=value2"
var params_string = url.split("?")[1] //UserName=value1&FirstName=value2
so first we split the string into a list like above which returns a list of the items which are separated by the "?" character, but we only need the second item(at index 1) so we add the [1] to the end to only store that bit.
We then split this again to get the individual parameters.
var params_string_list = params_string.split("&")
["UserName=value1","FirstName=value2"]
which returns a list as above, again need to break that down i would make it into an object like so :
var params = {}
for(var i =0;i < params_string_list.length;i++ ){
var temp = params_string_list[i].split("=") // looks like ["UserName","value1"]
params[temp[0]]= temp[1]
} //params now looks like {"UserName":"value1","FirstName":"value2"}
as this makes it easy to access and use.
we can then do the following to set the values in the form:
if(params.UserName){
$('#Username').val( param.UserName );
}
if(params.FirstName){
$('#FirstName').val( param.FirstName );
}
if statments are there to check that the value exists in the object so we don't sent the value to "undefined" by accident.
Hope this helps.

How can I prepopulate the remainder of forms based on user input from a first form?

So what I'd like tot do is have a list of forms that show up based on what the user picked in a page before. Now after entering the information in the first form, I would like to give the option of repeating that information for the additional forms . Ex.:
activity 1
Name 1
Name 2
Email
activity 2
Name 1
Name 2
Email
You can see how it can become redundant and tedious if you sign up for many activities. How would I do this in django if possible or javascript if i need to or even html5.
You could do this with just HTML5 and JavaScript (I have no idea what Django is, but this'll be easier if Django is a server-side language that can access form data).
I would make the action attribute of the <form> element in the first webpage lead to the second webpage so that the second webpage would have the GET parameters of that form data, and then in the JavaScript of the second webpage, use those GET parameters to put in data into the form. Here's an example:
tester1.html:
[...]
<form action = "tester2.html">
<input name = "realname" />
<input name = "screenname" />
<input type = "submit" />
</form>
[...]
tester2.html:
[...]
<script>
var form;
window.onload = function() {
var url = document.location.href;
var keys = url.substring(url.indexOf("?")+1, url.length).split("&");
form = document.getElementsByTagName("form")[0];
for (var i = 0; i < keys.length; i++) form[keys[i].substring(0, keys[i].indexOf("="))].value = decodeURIComponent(keys[i].substring(keys[i].indexOf("=")+1, keys[i].length));
};
</script>
[...]
<form>
<input name = "realname" />
<input name = "screenname" />
<input type = "password" name = "password" />
<input type = "submit" />
</form>
[...]

How to get values from posted html form using javascript

I have two html forms and I am posting input data from one html form to another html form.I want to retrieve values of variables that was posted using form 1 on the form 2.
<form name ="form1" id ="form1" method ="post" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
My question is how to get the value of the hidden variable sendToForm2 on form 2 once it is posted from form 1 to form 2 using javascript.
You can't use POST method because with a plain HTML page you do not have HTTP headers but HTML page code itself and URL (with query string).
What you can do is to use GET instead of POST then parse query string to extract them:
<form name ="form1" id ="form1" method ="GET" action = "form2.html>
<input id ="sendToForm2" type ="hidden" value ="send this to form2"/>
</form>
Then in your form2.html you can use this function (from this post on SO) to parse query string:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Now (let me use jQuery) you can access them with this:
<form ...>
<input id ="sentFromForm1" type ="hidden" value =""/>
</form>
</script>
$("#sentFromForm1").val(getParameterByName("sendToForm2"));
</script>

Categories

Resources