Concat Form Field Values - html

Hopefully I'm not repeating this question in anyways. But I am trying to get a form section with its name values and field vales to put as a single concat string. So like
Form Input:
First Name: John
Last Name: Smith
Fields 5 - 10.. etc
String Output:
FirstName=John&LastName=Smith&Field2=Value2&Field_etc=Value_etc
I tried
var inputArray = $("form#form :input").each(function () {
var input = $(this);
console.log(input.attr('name') + ":" + input.val());
});
Which outputs a test value correctly in the console.log as
firstName:John
lastName:Smith
but I'm struggling on the next bit of code that will help console.log it as a combine array string. Not sure if this is a for loop or something that helps the next step.

See comments in code below, maybe this might help you get on the right track...
The main cool thing here is to store submission data as an object and then use $.param() to convert submission to url string.
// on form submit
$(document).on('submit', '#form', function(e) {
// prevent form default submit action
e.preventDefault();
// set empty submission object
let submission = {};
// for each of this form submit event target object entries as key/field
for (const [key, field] of Object.entries(e.target)) {
// if object entry (field) has a name attribute
if (field.name) {
// add name/value to submission object
submission[field.name] = field.value;
}
}
// convert submission object to url params string
var paramsStr = $.param( submission );
// log the string
console.log(paramsStr)
});
<form id="form">
<input name="firstName" value="John" type="text" />
<input name="lastName" value="Smith" type="text" />
<input name="userName" value="johnsmith" type="text" />
<button type="submit">Submit</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Loop through the input elements and concatenate the name and value:
const inputs = document.querySelectorAll('#form input')
let msg
inputs.forEach(inp => {
inp.onkeyup = () => {
msg = 'String Output: '
inputs.forEach(i => msg += `${i.name}=${i.value}&`)
console.clear()
console.log(`\r\n${msg.slice(0, -1)}\r\n\r\n`)
}
})
input {
display: block;
margin-bottom: 8px;
font:18px/1.2em Arial;
}
<form id='form'>
<input name='FirstName' placeholder='First Name' />
<input name='LastName' placeholder='Last Name' />
<input name='Example1' placeholder='Example 1' />
<input name='Example2' placeholder='Example 2' />
</form>

Related

While user enters a value separated by comma in an input fields. The how to display the out put in list format

Here in this input fields. While user enters a value which is separated by a comma. For example like "apple,Banana,grapes,mango". So here if user enters the value in this format. Then I want to display the output in list format like
apple
Banana
grapes
mango
So if it can be done please let know how to do this. Below is my code where I have tried
<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>
<script>
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input values
//Now construct a quick list element
var li = "<li>" + text + "</li>";
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(li);
}
</script>
You were almost there, but you can not append HTML in strings, you need to create proper list item objects and append those:
document.getElementById("add").onclick = function() {
// cache the list
const list = document.getElementById("list");
//First things first, we need our text:
const items = document.getElementById("idea").value.split(','); //.value gets input values, .split(',') makes it an array of values
// foreach entry in the text array, create and append an li
for (const item of items) {
const li = document.createElement('li');
li.textContent = item;
list.appendChild(li);
}
}
<input type='text' id='idea' />
<input type='button' value='add to list' id='add' />
<ul id='list'></ul>

Appending access code input into URL as utm tag

I'm currently building a landing page with an access code form field.
I'm stuck on finding a way to get the access code entered into a form to be appended as a tag on the url.
Enter "12345" into field and on submit direct to url "www.website.com/?code=12345"
Below is the code I have so far - :
<script>
function btntest_onclick(){
if (document.getElementById('input-code').value == '1234','5678','9809') {
var domain = "http://www.website.com?";
var data = $(this).serialize();
window.location.href = url
}
else {
alert ( 'not found' );
}
};
</script>
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>
Any advice on this would be greatly appreciated!
Thanks.
You have a few problems in the code:
The if containing document.getElementById('input-code').value == '1234','5678','9809'. That's not a valid conditional statement in JS. I assume you were trying to test if the value was equal to any of the strings, which can be done using || (A logical "or").
The code was never added to the end of the URL.
You never defined the url variable you were redirecting to.
Here's a commented version that should explain some ways to do this:
function btntest_onclick() {
// First, we assign the value to a variable, just to keep the code tidy
var value = document.getElementById('input-code').value
// Now we compare that variable against each valid option
// if any of these are true, we will progress
if (value === '1234' || value === '5678' || value === '9809') {
// Use a template literal (The ` quotes) to build the new URL
var url = `http://www.website.com?code=${value}`
// This could also be written as:
// var url = "http://www.website.com?code=" + value
// Navigate to your new URL (Replaced with an alert as a demonstration):
alert(url)
// window.location.href = url
} else {
// Otherwise, show the alert
alert('not found')
}
}
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>

how frequently pattern attribute will be validating the text entered in html input

when i am doing a input field validation using pattern , how frequently the value will be validated . i would like to know whether it will validate on (keyup) or (change)
for ex:
<input type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />
i would like to know whether the text i enter will be validated on each keystroke ?
The pattern attribute is checked only upon submission the form or when you press enter on the input tag, so only on the enter key's stroke you might say.
If you want it to be validated on every keypress, keyup or onchange, you can set the corresponding attribute to validate the input like so:
<input keyup="validate(this)" />
...
<script>
function validate(x)
{
regex = /[a-zA-Z0-9]+/;
window.alert(x.value.match(regex) == null);
}
</script>
If I understand correctly your issue, you are trying to check the value entered "real time".
In the case, you could use input event to get value changed.
// Add error message element after input.
$('#input_email').after('<span class="error-message">Please write your message error here!</span>')
$('#input_email').on('input', function (evt) {
var $regex=/^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$/;
var value = evt.target.value;
if (value.length === 0) {
evt.target.className = ''
return
}
var result = value.match($regex);
if (result) {
evt.target.className = 'valid'
} else {
evt.target.className = 'invalid'
}
})
input.invalid + .error-message {
display: initial;
}
.error-message {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input_email" type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />

HTML "this" versus AngularJS ng-model

We are in the process of converting a very old ColdFusion application that made convenient use of "this" in conjunction with a function that did formatting:
<td>$<input type="text" name="txtTaxProration" id="txtTaxProration" value="0.00" alt="Tax Proration" onblur="dollarBlur(this);"></td>
The dollarBlur function would convert the numeric input to currency, i.e if the user entered 123, it was converted to 123.00; 23.45 was left as 23.45. This made the reference on the HTML side easy, but even easier in the actual function as the name of the element did not have to be specified. Is there some analogous way to do this in Angular?
<td>$<input type="text" ng-model="NetSheetDetail.TxtHomeWarranty" name="txtHomeWarrantyPolicy" id="txtHomeWarrantyPolicy" value="0.00" ng-change="angularDollarBlur(this)" ng-model-options="{ updateOn: 'blur' }"></td>
The following works fine, almost, HTML
<input type="text" ng-model="NetSheetDetail.TxtHomeWarranty" ng-change="reCalcX('NetSheetDetail.TxtHomeWarranty')" ng-model-options="{ updateOn: 'blur' }" ></td>
Controller
$scope.reCalcX = function (propName) {
alert($scope.$eval(propName));
$scope['propName'] = 666;
};
$scope.$eval(propName) does correctly reflect what was entered on the webpage ($scope['propName'] is undefined). However, $scope['propName'] doesn't appear to work - the change is not reflected back in the webpage.
Yes, simply pass the model.
ng-change="angularDollarBlur(NetSheetDetail.TxtHomeWarranty)"
$scope.angularDollarBlur = function (model) {
console.log(model);
}
Here's another example:
angular.module('app',[]).controller('myController', function ($scope) {
$scope.NetSheetDetail = {
TxtHomeWarranty: 'Hello World!'
};
$scope.angularDollarBlur = function (text, obj, prop) {
alert(text);
obj[prop] = 'Nope.';
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myController">
<input type="text" ng-model="NetSheetDetail.TxtHomeWarranty" ng-change="angularDollarBlur(NetSheetDetail.TxtHomeWarranty,NetSheetDetail,'TxtHomeWarranty')" />
</div>

How can I process a form using Google Apps Script?

I am a total noob when it comes to GAS, but I want to pass a form to a local JS function (to validate the data), which then calls a Google function (to add it to a spreadsheet).
Problem is: I can't even get the values out of the form!
My code is like this at the moment:
index.html:
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<div>
<form id="register" action="javascsript:void(0)" onsubmit="validateForm(this)">
Email: <input type="text" name="email" placeholder="someone#example.com" /><br/>
<p id="emailtext"></p><br/>
Smartschool URL: <input type="text" name="url" /><br/>
<p id="urltext"></p><br/>
<input type="submit" value="Submit" />
</form>
</div>
<?!= include('Javascript'); ?>
Javascript.html:
<script>
function validateForm(form) {
// THIS IS NEVER POPPING UP
alert(form.email);
return false;
}
</script>
GoogleCode.gs:
function doGet(e) {
return HtmlService.createTemplateFromFile('Page').evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
I added a console.log statement to the JavaScript, and looked at the log in my Google Chrome browsers console, and it shows that a form object is getting passed.
I added this line:
console.log('form: ' + form);
To your Javascript file:
<script>
function validateForm(form) {
console.log('form: ' + form);
// THIS IS NEVER POPPING UP
alert(form.email);
return false;
}
</script>
The browser console prints:
form: [domado object HTMLFormElement FORM]
So, the form object is getting passed. You can enumerate all the properties in the Form object to see what is in there, and available to retrieve.
for (var thePropurtees in form) {
console.log('thePropurtees: ' + thePropurtees);
};
You'll get a real long list of everything in the Form object, and you'll notice that email is not in the list. What is in the list is an elements property, that turns out to be another object inside the form object. There is an elements object inside of the form object.
If I enumerate the form elements:
for (var thePropurtees in form.elements) {
console.log('thePropurtees: ' + thePropurtees);
};
I get this:
thePropurtees: 0
thePropurtees: 1
thePropurtees: 2
thePropurtees: item
thePropurtees: email
thePropurtees: url
thePropurtees: namedItem
So, your email data must be in a sub object.
I was able to get the value out of the email input field with this:
console.log('the email value: ' + form.elements.email.value);
There are three levels of objects you need to access, before you can get at the values.
1) Form object
2) Elements object
3) Input object (email)
Your alert would need to be like this:
alert(form.elements.email.value);