Can I add a required passcode to my HTML form? - javascript

I want to put an HTML form on my website for people to send in their RSVP to a party invite. I want to require them to put in a passcode (that will be printed on their invite) before they can submit the form. Is there a way to set a field requirement to an exact match of a pre-specified pin # or password using purely HTML (and JavaScript if necessary)?
For sake of an example, let's simply say I want the person's name and a yes or no for their RSVP.
<form>
Name:
<input type="text" name="name">
RSVP:
<input type="radio" name="rsvp" value="yes">Yes<br>
<input type="radio" name="rsvp" value="no" checked>No<br>
Secret Word:
<input type="password" name="secretWord">
</form>

Yes, you would have to use Javascript, so you would want
function check(){
var pass = document.getElementById("pass_box").value;
if(pass == "Y o u r p a s s w o r d"){
// Do stuff
}else{
// Dont do stuff
}
}
and your html code would look like this:
<form>
Name:
<input type="text" name="name">
RSVP:
<input type="radio" name="rsvp" value="yes">Yes<br>
<input type="radio" name="rsvp" value="no" checked>No<br>
Secret Word:
<input type="password" id="pass_box" name="secretWord">
<button onclick="check()">Submit</button>
</form>
But this isnt very secure, because someone could just look at your code and see the password, but if its just for a party, it should be fine!
Anyway, there is your code! Hope this helps!

Related

Can't get Result to show with HTML Forms and Javascript

I'm trying to get my results to show up in the text box inputs as per my assignment but I can't get them to show up at all. The math isn't showing up at all so my big issue is that I can't get the code to show up in the box.
document.querySelector.("#buttonS").addEventListener("click", function(e) {
if (document.querySelector("#gallons").reportValidity()) {
let gallons = document.querySelector("#gallons").value;
if (document.querySelector("#quarts").checked) {
quartsTotal = gallons * 4;
document.querySelector("#quartsResult").placeholder = `quartsTotal`);
} else if (document.querySelector("#pints").checked) {
} else if (document.querySelector("#cups").checked) {
}
}
});
<form id="bakimg">
<input type="number" step=".01" min="0" id="gallons" required><label for="gallons"> How many gallons of milk do you have?</label>
<br>
<br>
<label for="conversion">Which conversion would you like?</label><br>
<input type="radio" value="quarts" name="gallonsC" checked><label for="quarts">Quarts</label>
<input type="radio" value="pints" name="gallonsC"><label for="pints">Pints</label>
<input type="radio" value="cups" name="gallonsC"><label for="cups">Cups</label>
</form>
<br>
<button type="button" id="buttonS">Submit</button><br>
<h1>Results</h1>
<br>
<input type="text" id="quartsResult" placeholder=""><label for="quartsResult">Quarts</label><br>
<input type="text" id="pintsResult"><label for="pintsResult">Pints</label><br>
<input type="text" id="cupsResult"><label for="cupsResult">Cups</label>
</div>
Check your syntax and make the following changes:
Check the browser console for errors and use the appropriate syntax:
document.querySelector.("#buttonS")
should be written like this:
document.querySelector("#buttonS") // No . after querySelector
Check the extra parentheses:
document.querySelector("#quartsResult").placeholder = `quartsTotal`); // <-- Remove the closing parens
Add the proper IDs to the HTML input elements (quarts, pints, cups):
<input type="radio" value="quarts" name="gallonsC" checked id="quarts">
<input type="radio" value="pints" name="gallonsC" id="pints">
<input type="radio" value="cups" name="gallonsC" id="cups">
Remove the backticks in order to use the variable value (otherwise quartsTotal is still a string):
`quartsTotal` -> quartsTotal
// Perhaps this is what you meant:
`${quartsTotal}`
Good luck with the assignment!

Formspree Profanity Filter

I am using formspree for a contact sheet on my site, and I am wondering if there is a way to use javascript to block profanity from being sent on the sheet, or a way to block specific words at all. The code I have is super basic so far:
<label>
Your name:
<input type="name" name="Name">
</label>
<label>
Your email:
<input type="text" name="Email">
</label>
<label>
Your message:
<textarea name="message"></textarea>
</label>
<button type="submit">Send</button>
Ideally I would want to be able to block profanity on the Your Message area. I know you can do this on formspree if you have a premium account but I am wondering if there's anyway I can do it within the code. Thank you!
You can make JS code which will work onchange of your message, if last symbol isn't letter (word is finished)read it and if it find some bad word delete it. Also you can use JQuery or write that yourself.
Also JQuery word filter
Jquery page with that function
I gave it a go using Vanilla JavaScript, but I'm not too sure if this is what you wanted. Either way, hope it helps:
<!DOCTYPE html>
<html>
<body>
<label>
Your name:
<input type="name" name="Name">
</label>
<label>
Your email:
<input type="text" name="Email">
</label>
<label>
Your message:
<textarea id="msg" name="message" ></textarea>
</label>
<button onclick="check()" type="submit">Send</button>
<script>
function check() {
const black_list = ["Pineapple Pizza"];
var description = document.getElementById("msg").value;
console.log(description);
let profane = black_list.some(word => description.includes(word));
console.log(profane);
}
</script>
</body>
</html>

display html form values in same page after button

i make a html site. there is questions on the site. i made it with form .After clicking on the button, I want to see all of the answers on the same page.i dont want as alert. how can i do it?
I apologize for the misspellings.
<script>
function findSelection()
{
var serieList=document.getElementsByName('serie')
for (var i=0; i<serieList.length;i++)
{
if(serieList[i].checked)
{
}
}
var markaList=document.getElementsByName('marka')
for (var i=0; i<markaList.length;i++)
{
if(markaList[i].checked)
{
alert(markaList[i].value)
}
}
var yerList=document.getElementsByName('yer')
for (var i=0; i<yerList.length;i++)
{
if(yerList[i].checked)
{
alert(yerList[i].value)
}
}
var nasilList=document.getElementsByName('nasil')
for (var i=0; i<nasilList.length;i++)
{
if(nasilList[i].checked)
{
alert(nasilList[i].value)
}
}
}
</script>
<html>
<head>
<title>Web Tasarım Anketi </title>
</head>
<body style="background-color:#d3ea93">
<center> <h1 style="color:red"> ANKET </h1> </center>
<form >
<fieldset><legend>Soru 1 </legend>
En sevdiğiniz yabancı dizi? </br>
<label> <input type="radio" name="serie" value="Game of Thrones">Game of Thrones </label>
<label> <input type="radio" name="serie" value="Person of İnterest">Person of Interest </label>
<label> <input type="radio" name="serie" value="South Park">South Park </label>
<label> <input type="radio" name="serie" value="Black Mirror">Black Mirror </label>
</fieldset>
</form>
<form >
<fieldset><legend>Soru 2 </legend>
En sevdiğiniz bilgisayar markası? </br>
<label> <input type="radio" name="marka" value="Asus">Asus </label>
<label> <input type="radio" name="marka" value="HP">HP </label>
<label> <input type="radio" name="marka" value="Toshiba">Toshiba </label>
<label> <input type="radio" name="marka" value="Dell">Dell </label>
</fieldset>
</form>
<form>
<fieldset><legend>Soru 3 </legend>
Nerede yaşamak istersiniz?</br>
<label> <input type="radio" name="yer" value="Türkiye">Türkiye </label>
<label> <input type="radio" name="yer" value="Mars">Mars </label>
<label> <input type="radio" name="yer" value="Avustralya">Avustralya </label>
<label> <input type="radio" name="yer" value="Yeni Zelanda">Yeni Zelanda </label>
</fieldset>
</form>
<form>
<fieldset><legend>Soru 4 </legend>
Nasıl ölmek istersiniz?</br>
<label> <input type="radio" name="nasil" value="Araba Kazasında ">Araba Kazası </label>
<label> <input type="radio" name="nasil" value="Uzay Boşluğunda">Uzay Boşluğunda </label>
<label> <input type="radio" name="nasil" value="Ecelimle">Ecelimle </label>
<label> <input type="radio" name="nasil" value="Maganda Kurşunu">Maganda Kurşunu </label>
</fieldset>
</form>
<input type="button" id="btnKaydet" value="Kaydet" onclick="findSelection()"></input>
</body>
</html>
You can use javascript to achieve this but ultimately you want to learn a server-side programming language, like php. To me php is the best option.
If you Google form and click the mozilla device docs for it you'll see an attribute called action, this attribute tells the form where to go or what to do (with inline javascript, but I highly recommend against this). You'll also find an attribute called method. Method is responsible for how the form handles the input values. The two most common values are post and get.
I usually only ever use post, because I'm posting the data to a script.
The most common use is something like
<form method="post" action="/area/scripts/post/form.php">
However, getting really fun with an mvc, would more look like:
<form method="post" action="<?php echo $this->getFormAction(); ?>">
Then in your form.php page you handle the data. To see what I mean, place this in your form.php for now:
<?php
var_dump($_POST) ;
This will display your form data.
To link it back to your idea of displaying on same page, you can also use ajax, however this means including jquery into your site. It 100% makes life easier but it does increase your sites size. Of course you can opt for the .min script but still, you include in every page, so..
Anyway. Using pure html I'm not sure is possible, javascript is a browser side programming language and I'm not sure entirely if you can assign values dynamically, you probably can but I'm no javascript expert.
I recommend using php for this as it also makes it secure (if you follow convention and do it correctly using safe code)
Also, I prefer this as a comment as an actual answer because it doesn't directly deal with your problem or its associated tags, but the character limit is not enough for a comment like this. Feel free to downvote if preferred and I'll simply remove if it gets to -3
Update after seeing comment
To combine variables in javascript you use + to concat strings.
E.g.
var message = document.getElementById('myId') + ' ' + document.getElementById('myIdTwo');
alert(message);
This only an example of how to use, but this should be what you're looking for.
Good luck!
you can do it via jquery give all your fields id
and write like this
<script>
$(document).ready(function()
{
$("#Button1).click(function()
{
$("#abc1").val($("#abc").val());
})
</script>
<body>
<input type="text" id="abc" />
<input id="Button1" type="button" value="button" />
<input type="text" id="abc1" />
</body>

How to validate with Javascript?

Thanks to having to work so much, I am completely confused on JavaScript. I have tried so many things and have not gotten my form to validate even once. I have to use plain JavaScript to:
**Validate the email - the email must have # and the domain should be yahoo.com
Phone No.: Must contain exactly 10 digits
Age: Must be a positive number less than 120
The validation should happen when the user submits the form. In case any of the above validation fails, the corresponding fields should be highlighted in red
If the validation is successful, the page should redirect to http://yahoo.com**
I'm not looking for someone to necessarily give me the exact answer, but push me in the right direction, because I do have a basic understanding of JS.
<!DOCTYPE HTML>
<div id="form">
<form name="myForm" action="http://fsu.edu" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function ValidatemyForm()
{
var email = document.myForm.email;
var phone = document.myForm.phonenumber;
var age = document.myForm.age;
}
{
age = age.replace(/[^0-9]/g, '');
if(age.length != 10)
{
alert("not 10 digits");
}
else {
alert("yep, its 10 digits");
}
}
</script>
</head>
<div id="header">
<hr id="HR1">
<h1> Web Programming: Assignment 3 </h1>
<p> Form Validation with Javascript </p>
<hr id="HR2">
</div>
<div id="input">
First name: <br>
<input type="text" name="firstname">
<br>
Last name: <br>
<input type="text" name="lastname">
<br>
FSU Email: <br>
<input type= "text" name="email">
<br>
Phone No.: <br>
<input type="numbers" name="phonenumber">
<br>
Age: <br>
<input type="numbers" name="age">
</div>
<hr id="HR3">
<br>
<div id="Sex">
Sex: <br>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br>
<input type="radio" name="sex" value="other"> Other
</div>
<hr id="HR32">
<div id="languages">
Programming languages you want to learn: <br>
<input type="checkbox" name="python" value="python"> Python
<br>
<input type="checkbox" name="java" value="java"> Javascript
<br>
<input type="checkbox" name="C++" value="C++"> C++
<br>
<input type="checkbox" name="lisp" valie="lisp"> Lisp
</div>
<hr id="HR32">
<div id="submit">
<input type="Submit" value="Submit">
</div>
<hr id="HR12">
</form>
</div>
Aneshia,
You have a few problems. First the function listed in the "onsubmit" attribute of your form does not match your javascript function. Also there are some problems with your {} braces. After you get that fixed be sure to call .value after your form elements to get the value of the input ie. (document.myForm.email.value).
Here is the code with some fixes:
<form name="myForm" onsubmit="return validateForm()" method="post">
<head>
<link rel="stylesheet" HREF="C:\Users\Neshia\Desktop\CGS3066\Form Validation Style Sheet.css" TYPE="text/css">
<script>
function validateForm() {
var email = document.myForm.email.value;
var phone = document.myForm.phonenumber.value;
var age = document.myForm.age.value;
console.log(age)
var okToSubmit = true;
age = age.replace(/[^0-9]/g, '');
if (age.length != 10) {
alert("not 10 digits");
okToSubmit = false;
} else {
alert("yep, its 10 digits");
}
if (age > 120 || age < 0) {
alert("Must be a positive number less than 120");
okToSubmit = false;
}
return okToSubmit;
}
Another thing that may help is to bring up the javascript console in your browser and run your function manually in the console by typeing 'validateForm();'
You may be intrigued to note that html5 now validates some of these forms so you do not need to use Javascript.
See HTML Form Validation
You asked about email, age and phone.
Consider the following examples::
<form>
<input type="email" name="email" pattern=".*#yahoo\.com"> <br>
<input type="number" min="18" max="120" name="age"> <br>
<input type="tel" name="phonenumber"> <br>
<input type='submit'>
</form>
If you want the fields to be required you could use
<form>
<input type="email" name="email" pattern=".*#yahoo\.com" required> <br>
<input type="number" min="18" max="120" name="age" required> <br>
<input type="tel" name="phonenumber" required> <br>
<input type='submit'>
</form>
See http://diveintohtml5.info/forms.html
In your comments a few days later, you mentioned needing to do this in Javascript. I think the best way is still using HTML5 and a clever way to do this if you have to use javascript might be to set the input attributes through javascript. Something like this could get you started on the logic.
While I generally do not like getting this specific in the code, I commented things so you can get a general feel for how you can work with data in javascript.
function validate(event){
// First we stop the form from even submitting until we run the code below
event.stopPropagation();
// Here we are going to place a reference to the objects we want to validate in an array
var references = ['email','age','phonenumber'];
// Now we are going to grab our list of inputs from the page
var inputs = document.getElementsByTagName('input');
// We run through a for loop to look for specific elements
for(i = 0; i < inputs.length; i++){
/*
This line simply asks, is the 'name' of this element inside our references array.
This works by using the indexOf function which is built into Javascript.
indexOf simply provides the index where it finds the phrase you are looking for.
In this example, we are using it to see if an index exists by checking it against negative 1
*/
if(references.indexOf(inputs[i].getAttribute('name')) > -1){
// A switch block lets you present a different outcome based on the criteria being looked for
switch(inputs[i].getAttribute('name')){
// In this case we see if we get an email named element
case 'email':
// We set the attributes to match our requirements for this email element and so on through this switch block for age and phonennumber
inputs[i].setAttribute('type','email');
inputs[i].setAttribute('pattern','.*#yahoo\.com');
break;
case 'age':
inputs[i].setAttribute('type','number');
inputs[i].setAttribute('min',18);
inputs[i].setAttribute('max',120);
break;
case 'phonenumber':
inputs[i].setAttribute('type','tel');
break;
}
// When we are all done, we set the elements to be required
inputs[i].setAttribute('required',true);
}
}
// Now we submit the form
event.submit();
}
<form>
<input type="text" name="email"> <br>
<input type="text" name="age"> <br>
<input type="text" name="phonenumber"> <br>
<input type='submit' onclick='validate(event)'>
</form>
<input type='text' id='txtEmail'/>
<input type='submit' name='submit' onclick='Javascript:checkEmail();'/>
<script language="javascript">
function checkEmail() {
var email = document.getElementById('txtEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
}
</script>

Send JavaScript Data to PHP Page

So I am new to JS and I am trying to take in a small amount of user input on a JS form. This input will then go to a PHP page as parameters for a result return on the PHP page.
I have been looking at tutorials and examples and I believe my form is named and labeled correctly, but I cannot seem to pull the form data, let alone send it to another page. I have been searching for an hour now with still no luck. :(
For reference, my JS form is page1.html and my PHP form that needs the data is page2.php. (in the same filepath)
Below is my Form code, the script at the top is just my attempt at the getting the data.
If someone could show me how to send form data to a "page2.php" I would be be very thankful!
All I need is the two text box inputs as well as the gender type.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults () {
var minWeight = form.minWeight.value;
var maxWeight = form.maxWeight.value;
var genderType = form.genderType.value;
alert ("Weight Range: " + minWeight + " - " + maxWeight + "\n for all " +
genderType + "s" );
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
Enter minimum weight:
<input type="text" name="minWeight" value="0">
<BR>
Enter maximum weight:
<input type="text" name="maxWeight" value="999">
<BR>
Select gender
<input type="radio" name="genderType" value="male"/>
Male
<input type="radio" name="genderType" value="female"/>
Female
<BR>
<INPUT TYPE="button" NAME="button" Value="Submit" onClick="testResults(myform)">
</FORM>
</BODY>
</HTML>
*If the code to send form data is a little tricky, please explain it so that I can understand what is occurring.
Thank you very much!
The reason your JavaScript doesn't work is because you named your form myform but you're trying to access form.
That said, you shouldn't be using JavaScript for this. Just a simple form will do:
<form action="page2.php" method="post">
<p><label>Enter minimum weight: <input type="number" name="minWeight" value="0" min="0" required /></label></p>
<p><label>Enter maximum weight: <input type="number" name="maxWeight" value="999" min="0" required /></label></p>
<p>Select gender:
<label><input type="radio" name="genderType" value="male" required /> Male</label>
<label><input type="radio" name="genderType" value="female" /> Female</label>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
Your PHP script can then reference $_POST['minWeight'], $_POST['maxWeight'] and $_POST['genderType'].

Categories

Resources