Set hidden form field from URL paramater - javascript

I'm trying to set the value of a hidden field in my form through a URL parameter.
Here is the form:
<form accept-charset="UTF-8" action="/thanks" class="infusion-form" method="POST">
<input name="inf_field_LeadSourceId" type="hidden" value="null" />
<input class="infusion-field-input" id="inf_field_FirstName" name="inf_field_FirstName" placeholder="First Name *" type="text" required/>
<input class="infusion-field-input" id="inf_field_Email" name="inf_field_Email" placeholder="Email *" type="text" required/>
<div class="infusion-submit">
<button class="infusion-recaptcha" type="submit">Submit</button>
</div>
</form>
I need to set the value of this field, specifically:
<input name="inf_field_LeadSourceId" type="hidden" value="null" />
with a url parameter.
Ideally, I would like it to be something like this:
https://website.com/page?leadsource=123
So it would set that field to have the value of "123"
I tried doing this using the javascript code below, but no luck :(
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? 120 : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var LeadId = getParameterByName("leadsource");
jQuery(".infusion-form input[name='inf_field_LeadSourceId']").val(LeadId);
</script>
Any advice on how I can tweak my javascript to prefill my form with the URL parameter?

JavaScript isn't the best with URL parameters. If I'm understanding your question correctly, it'd probably be ideal for you to simply inject the parameter directly into the HTML field with PHP (requiring no JavaScript).
<input name="inf_field_LeadSourceId" type="hidden" value="<?php echo $_GET['leadsource']; ?>" />

Here's the javascript I used to base my solutions filling Infusionsoft hidden fields values.
Also may also try to debug your javascript flow to see if you're catching and parsing the value properly (for example, adding conlose.log(var) line).

Related

Forward GET parameter to next URL

I am building a form with HTML consisting of multiple pages, one per question (due to layout reasons). I use the 'GET' method to pass the parameters of the form input to next page, like this:
<form action="example.html" method="GET">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
This works fine and leads me to the URL
/example1.html?Machine=Input
On the next page, I use the same code as mentioned above (only different name and id for the input), but when I submit that page the parameters from the first page won't be redirected (of course). So the URL looks somewhat like this:
/example2.html?Amount=Input
I would need to have the parameters of the first page, too though. Basically looking like this
/example2.html?Machine=Input&Amount=Input
Is there a simple way for doing this with little Javascript or even without it? Thanks for your help
You could try adding hidden input elements to your form dynamically with javascript, created with name and value pairs from the GET parameters in document.location.search.
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) {
var steps = document.querySelectorAll('[step]'),
formStep,
formStepNo,
i;
for (i = 0; i < steps.length; i++) {
formStep = steps[i];
formStepNo = formStep.getAttribute('step');
if (step == formStepNo) {
formStep.style.display = 'block';
} else {
formStep.style.display = 'none';
}
}
}
var step = 1;
goTo(step);
function nextStep() {
step++;
goTo(step);
}
function backStep() {
step--;
goTo(step);
}
<form action="example.html" method="POST">
<div step="1">
<p>Step 1</p>
<input type="number" name="Machine" id="Machine" placeholder="Machine" />
<button onclick="nextStep()" type="button">Forward</button>
</div>
<div step="2">
<p>Step 2</p>
<input type="string" name="foo" placeholder="foo"/>
<button type="button" onclick="backStep()">Back</button>
<button type="button" onclick="nextStep()">Forward</button>
</div>
<div step="3">
<p>Step 3</p>
<input type="string" name="bar" placeholder="bar"/>
<button type="button" onclick="backStep()">Back</button>
<button type="submit">Submit</button>
</div>
</form>
Use this bit to get the parameters
How can I get query string values in JavaScript?
then this bit to add in the hidden form fields to the the form to pass along on the next submit
Create a hidden field in JavaScript
so something like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var Amount= getParameterByName('Amount');
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "Amount");
input.setAttribute("value", Amount);
document.getElementById("example2").appendChild(input);
<form action="example1.html" method="GET" id="example1">
<input type="number" step="0.1" name="Amount" id="Amount" placeholder="Amount">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
<form action="example2.html" method="GET" id="example2">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>

How do i create a simple Javascript Program that displays the value of <input type="text">?

I am new to javascript, and i only know c++ so far, but i know the logic but i just don't know the syntax on javascript
so i have this form :
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
when the user types his/her name how do i save the value to some variable and display it with javascript?
i have already tried using
function displayName(){
var username = getElementById("inputname").value;
document.write(username);
}
and i put
<script>displayName();</script>
below the form. it doesn't seem to work, how do i do it?
and how do i use:
<input type="submit"></input>
in relation to it?
Try this,
Javascript
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
}
HTML
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
<input type="button" onclick="displayName();"></input>
<span id="msg"></span>
By changing onclick="return displayName()" to onkeypress="displayName()" you will be able to see the changes on the spot.
change your html and js like this. onblur function call when user leaves the input from focus. get the enter value onblur
<span>Please type your name here: </span>
<input id="inputname" type="text" onblur="displayName();" value=""></input>
js
function displayName(){
var username = document.getElementById("inputname").value;
document.write(username);
}
you need to change your fucntion little bit..
getElementById() is not a direct function in javascript..use it with document object
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
return false;
}
on submit click
<input type="submit" id="btnSave" onclick="return displayName();" value="Save" />
<div id="msg" > </div>

data-bind multiple text boxes to display in one text box

I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>

Requesting specific values from an html input via Javascript

I'm trying to find a way to be able to do the following. I want to be able to get certain things from a form. In this case, I only want the "value" field and NOT the "name" field.
<div class="searchbox_team" style="margin: 0 0 10px 0; z-index: 50;">
<script type="text/javascript">
function customSearch()
{
var x = document.customSearch;
x.replace("customSearch=", "");
return x;
}
</script>
<form name="leSearch" action="/search/node/" onsubmit="return customSearch()" id="search-block-form" class="search-form">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="submit"/>
</form>
</div>
I have tried using the following in my function.
var x = document.customSearch.value;" but that is not working.
Can anyone shed some light on this?
It sounds like you want the value of the input for customSearch. If so then just use the following
var value = document.getElementById('edit-search-block-form-1').value;
Your input tag already has an id value hence the most efficient and simplest way to search for it is using getElementById.
hmm, so to get things from the form, you'll want to specifiy like so:
document.forms.leSearch.elements["customSearch"].value;
EDIT:
try adding a hidden field that stores the value onclick and then get that from the post or get array in your action file.. I think onsubmit call is to blame
<form name="leSearch" action="/search/node/" onclick="document.getElementById('myhiddenfield').value = customSearch()" id="search-block-form" class="search-form" method="post">
<input type="text" name="customSearch" value="" id="edit-search-block-form-1" class="searchbox_input" title="Enter the terms you wish to search for." />
<input type="hidden" value="" id="myhiddenfield" />
<input type="submit"/>
</form>
EDIT 2:
I think I figured it out.. the url was appending the field names because it was defaulting to "get" method mode.. set the action=/node/search/" and method="post"
<form method="post" action="/search/node/" onsubmit="this.action = '/search/node/' + document.getElementById('edit-search-block-form-1').value;">

Validating an HTML form with onClick added form fields

I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.

Categories

Resources