Create a form that collects info after data verification [duplicate] - javascript

This question already has answers here:
How can I get form data with JavaScript/jQuery?
(31 answers)
Closed 10 months ago.
I'm trying to create an HTML/JS action "choose your zip code from a list." If the user's zip code is found, they are brought to a form that collects their contact info and once the form is completed - is emailed to the form's administrator.
If the zip code isn't present, they are shown a window that says 'sorry, try here [insert URL here] instead.

This question is a bit redundant, because you're pretty much asking us to build the entire app for you, but you can validate zip codes like this:
const validZipCodes = ['000000']
const zipCode = document.getElementById('zipcode').textContent;
if (validZipCodes.includes(zipCode)) {
// Valid, now redirect
window.location = '/info' // any other link
} else {
// Maybe add custom alert
alert('Invalid zip code!');
}

My answer took to long but it's worthile to share anyway...
This is a demo showing the concept you asked for in your question.
Anyway if we want to discuss your idea there are some weak points. The list of allowed zips is no secret and is embedded on the page. Is it a critical leak? Do you want the list to be dynamic and served externally? you might do an ajax request here to feed that list but yet its logic would be transparent and easy to temper. Or you could use this form just as a messenger where it just forward your input to a service like tellMeIfThisZipIsAllowed(zip) so that the logic won't be known publicly but here you'd just need to collect the input, call the ajax function and do the redirect if its response is positive. But yet the redirect address would be known so you would be forced to check again the zip inside that step and kickout the user in case the zip isn't valid. Yet another weak approach. So the point is why do you need this frontpage before the rest of the registration and if its security measure should be hard to bypass or not.
So to make sure you understand that warning, you should really validate that zip inside the action following the next step (server side).
const allowed_zips = ['12345', '00000', '90210'];
function checkZip(){
document.querySelectorAll('.msg').forEach((o,i)=>{o.remove();});
const zip = document.getElementById('zip');
const msg = document.createElement('div');
msg.classList.add('msg');
if( allowed_zips.includes(zip.value) ){
msg.innerText = `Your Zip is valid.. redirecting to next step`;
}
else{
msg.innerText = `Your Zip is invalid`;
}
zip.after(msg);
//here we are redirecting to next step of registration form
//but I would recommend to pass the zip to it for further inspection
//like here through GET or using a different strategy with an hidden form
//to submit a POST action.
//window.location.href = "path/to/next/url?zip=${zip.value}";
}
<input id="zip" type="text" placeholder="Insert your zip code...">
<button type="button" onclick="checkZip();">Next step</button>

Related

Update value of INPUT in externally loaded FORM not working

total programming novice here - I don't know much of javascript, wasn't programming since university (about 10 years ago) - trying to solve one specific problem on my website.
I am using CRM Bitrix24 and I have an unsubscribe form from this CRM placed on my website. I need to setup the form the way that the email is loaded from URL parameter.
I have done that simply by loading the input and set input.value = "email from URL". My problem is that the form has some kind of validation, and even though there is a text filled in the input field, the form is giving me the error: Field is required.
Screenshot here: https://ibb.co/Ns33GVN
The code of external form look like this:
<script data-b24-form="inline/120/8y7xg2" data-skip-moving="true">(function(w,d,u){var s=d.createElement('script');s.async=true;s.src=u+'?'+(Date.now()/180000|0);var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})(window,document,'https://cdn.bitrix24.com/b7014957/crm/form/loader_120.js');</script>
My JS:
function emailPopup(){
var params = new window.URLSearchParams(window.location.search);
var email = params.get('email');
const emailCollection = document.getElementsByName("email");
for (let i = 0; i < emailCollection.length; i++) {
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
}
}
} window.addEventListener('load', function () {
emailPopup();
})
I tried to understand how the validation is done, but with no luck. The field has autocomplete = yes, so once it is submitted, next time it's not shooting the error, but the form is sent with the email submited at the first attempt, even though it is showing another one when hitting the SUBMIT button. It seems like it's only showing the email address from URL parameter, but in fact it's using wrong value, it's even empty (first attempt) or wrong (second attempt).
Is there a way how to force the field to pretend it was modified by user? Any ideas?
I have tried to setup similar environment here in jsfiddle: https://jsfiddle.net/e395wf6m/17/
Thanks a lot for any feedback!
I have a theory and it seems to be correct, as I tested it in your fiddle.
My theory is that the validation is done by firing a change event, so you need to trigger it. Luckily JavaScript let us do it:
if (emailCollection[i].name == "email") {
//emailCollection[i].focus();
emailCollection[i].value = email;
// to trigger the change event
emailCollection[i].dispatchEvent((new Event('change')));
}
As I said, it worked when I tested it on your fiddle, let me know if it works for you =]

python requests popup generating a key

I have just started my journey with Python and am just amazed at how much one can do in less than 50 lines of code.
I got stuck, however, writing an app which is to:
connect with a web site
log in using my credentials
fill a form
choose a link from the results returned by the form
use the link to confirm an appointment
use the link to book an appointment
I went all the way through but got stuck at point 6 above. Maybe this is due to something going wrong at point 5, so please let me start with what happens in step 4 :-).
I enter step 4 with the form site generating a list of available appointments. Those are links attached to buttons, like:
<a class="button strong" href="/your_account/confirm?CityId=500&VisitId=42204&HasReferral=False" target="popup"> click to book </a>
NOTE: the button opens a pop-up.
I use BeatifulSoup to pick one of the links, then I convert it to a dictionary
entry = {'CityId' : '500',
'VisitId' : '42204',
'HasReferral' : 'False'}
In step 5 I continue a session which I had created with Python's requests module and POST:
a = my_session.post( 'https://the_website.com/your_account/confirm', data = entry)
What is returned in the a object is the pop-up. In the the pop-up's code there is a function and a button, like the ones below:
accept = function () {
if (canRedirect()) {
var url = '/your_account/reserve?key=55924c2b-9b30-4714-ad6c-8f47c72893cd';
$.post(url, function(html) {
$("#dynamicReservationDivCntainer").html(html);
});
}
};
<button onclick="accept()" id="okButton" class="button strong right reserveConfirmButton">Click here to hit the deal</button>
So here is the step 6 and my problem. When I extract the site address and key from a.text, like in step 5 and POST it:
key_dict = {'key' : '55924c2b-9b30-4714-ad6c-8f47c72893cd'}
b = my_session.post( 'https://the_website.com/your_account/reserve', data = key_dict )
It turns out that b contains a site with something like : "Failure. The key already exists in the database. Please enter another key." and nothing gets booked.
Ah, please let me know if I missed something important in the story. I tried to extract what I believe is the crux of the matter and am afraid I may have oversimplified.

Specifying form for 'on form submit' trigger

I have two google forms, which send data to two tabs in a single spreadsheet.
I have set up a script with two functions. I would like the first function to run on submission of the first form. And, the second function to run on submission of the second form.
Problem is: when setting up a trigger onformsubmit, it does not allow you to specify which form.
Therefore, whenever completing the first form, it runs both functions.
Question: how can I restrict the functions from running only when the specific form is submitted?
As I suggested in the comments, you can determine the origin of the form submission by analyzing the response object's content.
Here is a basic example to illustrate : it will send you an email to tell which form has been submitted but you can of course use the same condition test to select the action you want to run.
function formSubmitOriginTest(e){
// Logger.log(JSON.stringify(e));
// example value : {"namedValues":{"Untitled Question 2":["test"],"Timestamp":["8/17/2014 11:22:47"]},"values":["8/17/2014 11:22:47","test"],"source":{},"range":{"rowStart":3,"rowEnd":3,"columnEnd":2,"columnStart":1},"authMode":{}}
if(e.namedValues["Untitled Question 2"]!=undefined){// only form B has one question with this exact title, that's enough to identify it.
MailApp.sendEmail(Session.getActiveUser().getEmail(),'form B has been submitted','');// optionally include the answers in the email body if you want
}else{
MailApp.sendEmail(Session.getActiveUser().getEmail(),'form A has been submitted','');// optionally include the answers in the email body if you want
}
}
Another way this can be done is by looking at the sheet name that comes in the response's event object via the range property. Here's an example of how I determined the form that triggered the submission:
// set the sheet name that stores the form responses you care about here:
function getSourceSheetName() { return 'Form Responses 1'; }
function submit(eventObj) {
var range = eventObj.range;
var eventSourceSheetName = range.getSheet().getName();
var givenSourceSheetName = getSourceSheetName();
// if the source sheet (from form response sheet) is not the same as the specified form response sheet, quit (return) so extra forms don't trigger the code
if (eventSourceSheetName.toUpperCase() !== givenSourceSheetName.toUpperCase() ) {
Logger.log('A different form just submitted data - quit code');
return;
}
// you now know which form submitted the response, so do whatever you want!
// ... your code goes here
}
Basically, this code grabs the name of the sheet that the Form response comes from via range.getSheet().getName(). Next, it checks if that name is a specified name we're looking for (specified in the function getSourceSheetName().
I think it's also possible to get the active sheet name via:
eventObj.source.getActiveSheet().getName();
In case you don't want to use "Range".
I hope this helps!
I was just looking at some documentation and found this:
Documentation forForm
It states:
Creates and returns a FormTriggerBuilder tied to the given form.
Also:
var form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
ScriptApp.newTrigger('myFunction')
.forForm(form)
.onFormSubmit()
.create();
onFormSubmit
That code seems to be tied to a specific form.

I just want my form to be key with a specific answer by my customer , how to?

I do not want to used captacha on my site. as such i would just like my customer to key a specific answer in the form that i have created.
For example = What is 3 + 4 ? and i only want the field to be key with number 7. for instance if my customer keyed any other number then 7, the form would not be submitted and would request for the right answer.
I'm trying to use spry widget to perform this trick but have failed multiple times even after changing the html code.
here's the code:
<span id="sprytextfield4">
<input type="text" name="huamn" id="huamn" />
<span class="textfieldRequiredMsg">
Please provide an answer
</span>
</span>
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "text", {minValue:7, maxValue:7, maxChars:1});
if you want to validate using javascript on the client, here's a quick and dirty way that I've used.
note: you still need to validate the same question on the server to ensure the spammer hasn't circumvented by disabling Javascript
jQuery
$('#submit').click(function (event) {
var color = $('#color').val().toLowerCase();
if (color != 'orange') {
alert('incorrect');
} else {
alert('yay!');
// submit the form
// BUT DON'T FORGET TO VALIDATE input.color AGAIN ON THE SERVER.
}
});
http://jsfiddle.net/g4Gu8/1/
if your site is of low importance to spammers... IE: not StackOverflow or Redit, you can typically get away with this type of validation and pretty much avoid getting spam. If your site becomes a direct target for attack, and bots are written to circumvent this very low level of protection, you should look into using one of the many pre-build captcha libraries out there and implement both the server side and client side validation. I for one can't stand image CAPTCHA's, so I prefer a method of "human verification" that is less intrusive.

Javascript Zip Code form for a delivery area?

I'm a total Javascript noob and will be taking a class next semester and learning it but in the mean time, I have a basic website Im doing for a local business. On it I need to make a form with just one input and a submit button that a potential customer can enter their zip code into and it will say whether or not they are in the delivery area. I have a list of about 30 zip codes.
Can someone point me in the right direction of where to learn this functionality quickly? I assume I just need to type those zips into some array or something like that and then I have the submit action check for a match or not. I understand the logic but I have no idea where to begin with the code as I am currently just a html/css static webpage guy.
Thanks alot in advance.
Dave
To learn how to assemble your form correctly check out this web site.
Then you can have your array of zip codes on the server and check if the submitted code is in that array. How you do that will depend on what server setup you have.
To do client-side validation, you could set it up and check in the JavaScript. It would be something like:
Form:
<input type="text" id="zipCode">
<input type="button" onclick="checkZipcode()">
JavaScript:
var zipcodes = [12345, 54321];
function checkZipcode() {
var i, validCode = false;
for(i = 0;i < zipcodes.length; i++) {
if (zipcodes[i] == document.getElementById('zipCode').value) {
validCode = true;
}
}
However, never rely solely on client-side validation. Make sure to also perform server-side validation.

Categories

Resources