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.
Related
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 =]
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>
I'm trying to create a basic time clock web app.
So far, I'm using this script to create this web app which takes the input values and puts them in this spreadsheet for the time stamping part.
I need it to use one of the values from the form and perform a lookup in this sheet (take the longId and find me the name) and return the (name) value to the html page as a verification for the end user that they were identified correctly. Unfortunately, I don't know enough to grasp what I'm doing wrong. Let me know if I need to provide more info.
Edit 1
I'm thinking that I wasn't clear enough. I don't need the user info from entry, I need the user from a lookup. The user will be entering their ID anonymously, I need to match the ID to their info, and bring the info back for them to verify.
Edit 2
Using the link provided by Br. Sayan, I've created this script using this spreadsheet as above to test one piece of this. The web app here spits out: undefined. It should spit out "Student 3" Still not sure what I'm doing wrong.
One way for the next button to grab the student input field:
<input type="submit" onclick="studentName(document.getElementById('student').value)" value="Next..."/>
That sends the value to this func in Javascript.html:
function studentName(value) {
google.script.run
.withSuccessHandler(findSuccess)
.findStudent(value);
}
Which sends it to a findStudent(value) in Code.gs
You do the lookup and the return value goes back to findSuccess( result ) back in Javascript.html. Handle the result from there.
Also consider keeping the stock preventDefault() code that comes with the Web App template in the Help > Welcome Screen.
Please try this one:
(source: technokarak.com)
Also please have a look at:
Retrieve rows from spreadsheet data using GAS
EDIT:
Please make these changes in your function and let us know.
function findValue() {
var data = SpreadsheetApp.openById("15DRZRQ2Hcd7MNnAsu_lnZ6n4kiHeXW_OMPP3squbTLE").getSheetByName("Volatile Data").getDataRange().getValues();
for(i in data) {
if(data[i][3] == 100000003) {
Logger.log("yes");
Logger.log(data[i][0]);
var student = [];
student.push(data[i][0]);
return student;
}
}
}
It is a complicated answer, I have had a lot of success with:
function process(object){
var user = Session.getActiveUser().getEmail();
var key = object.Key;
send(key);
}
function send(k){
var ss =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastR = ss.GetLastRow();
ss.GetRange(lastR,1).SetValue(k);
}
On your html button you will need to have inside the tags
onClick="google.script.run
.withSuccessHandler(Success)
.process(this.parentNode);"
In order for this to work, obviously you will need to have your fields named accordingly.
Edit: The only thing I did not include in the code was a Success handler, which will be in your html of the GAS script. This should point you in a direction that can resolve that.
Hope this helps.
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.
What I want to do is to have a form field that allows a person to try to guess from a picture what type of bird it is, and if they get it right, it tells them they got it right and gives them the code to be able to get a discount.
Here is the code I'm using within the head tags:
formCheck()
{
var birdName = document.forms[0].birdName.value
if (birdName == "red bellied woodpecker")
alert("That's Correct! Please enjoy 10% off your next purchase by entering the code NAMETHATBIRD92 during checkout.")
else
alert("That's isn't the correct answer! Make sure your answer is very specific and keep trying, you can guess as many times as you want.")
}
Here is what I have within the body tag:
Can you name this bird?
It works here:
www.madhatwebsolutions.com/namethatbird.html
It does not work here, where I really need it to work:
http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
This shouldn't be JavaScript.
Any potential customer will be able to right click and view your JavaScript source and retrieve the code without bothering with the guesswork.
You'll need to query a server with the user input, and the server will need to return a response indicating whether this input is correct or not.
You might want to look at either a normal HTML form submission, or venture into AJAX
Workflow:
User enters guess into textfield
Launch a request to http://yourserver.com/check_bird.your_server_language?guess=theTextFieldValue
Server returns either a success or failure indication
Display response to client
Other things to consider: Are you going to allow your customers to guess multiple times, or restrict them? Are you going to be showing several different birds or not?
in http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
<script type="text/javascript" src="birdname.js"></script> refers to 404 - check the file path
don't use document.forms
var birdName = document.getElementById('birdName').value;