Field Validation for specific input - salesforce-marketing-cloud

I am trying to validate a field based on the value for a partner referral code.
I have tried using the code below for my smart capture form on cloud pages from marketing cloud.
<script>
function validateForm() {
var x = document.forms["smartcapture-block-kxnnlxjo93j"]
["PartnerCode"].value;
if (x == "SJC") {
return true;
} else {
alert("Invalid Partner Referral Code - Make Sure You Use All Caps");
return false;
}
}
</script>
The form just submits, even if I don't use a partner code, or if I input the incorrect partner code.
The form id is "smartcapture-block-kxnnlxjo93j" and the input field id is "partnercode" that I want the function to execute on.

Try the following, you can get the value directly from the input field.
<script>
function validateForm() {
var x = document.getElementById("PartnerCode").value;
if (x == "SJC") {
return true;
} else {
alert("Invalid Partner Referral Code - Make Sure You Use All Caps");
return false;
}
}
</script>

Related

Need help to show a operation with user inputs in ruby on rails

So, my company is working in a rails fleet manager, and i'm struggling to show in real-time a simple operation of a unit (amount * value) in real time to the user.
This is the .haml file where the form is show to user:
What is the best way to do it?
I think this has nothing to do with Rails. You can simple create a 'change' event listener in the input fields of your form to calculate it. If you are using turbolinks then you can do something like this:
document.addEventListener("turbolinks:load", function() {
// Get the elements in DOM
var amount = document.getElementById("amount");
var unitValue = document.getElementById("unit_value");
var result = document.getElementById("result");
// Calculate and return unite values times amount.
function calculate_total(unit, amount) {
// If there is no value on input set 0 by default
if (unit == "") {
unit = 0
}
if (amount == "") {
amount = 0
}
return parseInt(unit) * parseInt(amount)
}
// Set the event listener to inputs on user keyboard input
amount.addEventListener("keyup", function(e) {
result.value = calculate_total(unitValue.value, amount.value)
});
unitValue.addEventListener("keyup", function(e) {
result.value = calculate_total(unitValue.value, amount.value)
});
})
This code is not tested, but is to give you the idea.

How to deal with if statement when one Form Response has no response in Google Script?

I'm trying to create a script that sends an email when someone submits a google form. The form includes an optional file upload that the script will then attach to the email as a pdf.
The issue I'm facing is how to ignore the process that creates the attachment if the response is empty.
Sample code below
function getIdFrom(url) {
var id = '';
var parts = url.split(
/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
);
if (url.indexOf('?id=') >= 0) {
id = parts[6].split('=')[1].replace('&usp', '');
return id;
} else {
id = parts[5].split('/');
var sortArr = id.sort(function (a, b) {
return b.length - a.length;
});
id = sortArr[0];
return id; //returns google doc id.
}
}
function onFormSubmit(response) {
var link = response.namedValues['Upload file'];
if (typeof link !== "undefined" && link.length > 0) { // I think it's here that's the issue
var uploadFileId = getIdFrom(link[0]);
var uploadFile = DriveApp.getFileById(uploadFileId);
var uploadFileType = (function () {
if (uploadFile.getMimeType().includes('image')) {
return uploadFile.getMimeType();
} else {
return 'application/pdf';
}
};
var attachArr = [uploadFile.getAs(uploadFileType)];
}
// etc etc send email.
}
Works fine if the user submits a form with an uploaded file.
However if the form is submitted without entering anything in the "Upload File" question, I'm getting a "TypeError: Cannot read property 'split' of undefined" at the getIdFrom(url) function I assume because it's still trying to pass link through getIdFrom() even though it shouldn't because it's undefined.
Weirdly it works perfectly fine when I use the two test inputs I have, one of which 'Upload File' exists but is empty and the other it doesn't exist at all.
I'm not sure what I'm missing here.
Also I have no doubt it's a messy way to do things but I'm getting there.
response.namedValues['Upload file'] is an object
even if it's empty it will have at least the length of >0
Workaround
Modify your if statement to
if (link[0].length > 0) {
...
}

Ways to load large amount saved data into an HTML page?

I have a timesheet that several of my employees use and fill out daily. I'd like to add the feature for them to be able hit 'Save' and then later on they can load what they saved back into the time sheet.
I have the save part working just fine. It just saves the data in the sheet to some tables in a database. The real issue/question I have is what is the best way to get this loaded back into the database? I've done some very simple save/load stuff before but only with a single field. I used an ajax call like this:
function grabTransportNum(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('tandt1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
All this does is pull out a single number and sets the value of 'tandt1' to whatever number is returned. Doing this for every field sounds easy enough, but depending on how much is saved, I may need to load data into 100+ fields. Having a function like this for every single field sounds absolutely awful, so I figure there must be a better way to go about this. Could I get some suggestions?
What you could do is instead of sending a single field from the server, send a JSON that has multiple fields, like:
{
"fields": [
{ "id": "tandt1", "value": "persisted value"},
//in here you'd have the rest of the fields in the same format
]
}
then change your function to something more like this:
function reloadFields(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var data = JSON.parse(req.responseText);
if (data && data.fields && data.fields.length > 0) {
for (var field,i=0;i<data.fields.length;i++) {
field = data.fields;
document.getElementById(field.id).innerHTML = field.value;
}
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
A tidy way to do it would be for the javascript on the page to set a flag for any field that is changed. Then when the employee submits the data, the only data which is actually sent is the change(s) made. So if you're using ajax, here's what I would suggest: for each edit the user makes, add the changes to an object which you will send via ajax when the user hits submit.

Ajax form requires two clicks on submit before fades out

So there is obviously something wrong in my syntax. Validation is ok. When I click submit the form sends email to me and then it deletes the value of my inputs. Everything is ok until now. But it does not fade out as it should. If I click on submit again, then it fades out. Thanks!
<script type="text/javascript">
$(document).ready(function () {
$('#form1').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter a value for name');
return false;
}
if (!email[0]) {
alert('Please enter a value for email');
return false;
}
if (!message[0]) {
alert('Please enter a value for message');
return false;
}
else {
$("#form1").ajaxForm(function () {
$("#formplic").fadeOut(1000, function () {
$(this).html("<img src='images/postauto3.png'/>").fadeIn(2000);
});
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
}
}
});
OK. I figured it out. The issue was that after else I stated again ajax.Form. I deleted that line and it works pefectly. So, if someone makes the same mistake as me, delete $("#form1").ajaxForm(function ().

Call two function in one onchange = not working

I have been searching how to put more than one function in onchange and I found how something like this for example: onchange = "function1(); function2();".
My problem here is I have followed what does the example like, but only function1 is working, function2 is not working. If I make it otherwise to onchange = "function2(); function1();", only function2 is working, function1 is not working, the same.
Any ideas guys?
Thanks.
The functions, I used Ajax:
function1(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp.open('get', '../template/get_name-opr.php?kode='+kode, true);
xmlhttp.onreadystatechange = function() {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
//alert(kode);
document.getElementById("code").innerHTML = xmlhttp.responseText;
}
return false;
}
xmlhttp.send(null);
}
function2(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp**1**.open('get', '../template/get_name2-opr.php?kode='+kode, true);
xmlhttp**1**.onreadystatechange = function() {
if ((xmlhttp**1**.readyState == 4) && (xmlhttp**1**.status == 200))
{
//alert(kode);
document.getElementById("code2").innerHTML = xmlhttp**1**.responseText;
}
return false;
}
xmlhttp**1**.send(null);
}
To solve my problem, I created two xmlhttp different. (xmlhttp and xmlhttp1).
Go through the link I gave, it seems to be problem with the way you are managing the xmlhttprequest objects, manage their instances properly, in your case because you are using the same xmlhttprequest for two simultaneous AJAX requests, only one of them is getting served. Either wait for one of them to get served or create two instances of the xmlhttprequest.
The statement xmlhttp.readystate = function() {...} obviously replaces the readystate property of that xmlhttprequest object, so on your second function, that is being replaced( because you are using the xmlhttprequest for both of them ). This is why you are seeing the funny behaviour.
Call function2() at the end of function1().
onchange = "function1()"
function1(){
...
function1 body;
...
function2()
}
Wrap the two function calls in one and call that function!
function myFirstFunction() {
//body
}
function mySecondFunction() {
//body
}
//Call this guy.
function myWrappedFunction() {
myFirstFunction();
mySecondFunction();
}