I'm trying to create a webpage where a user asked their name(textbox) and gender(radio buttons) on the front page. This will then link to a new page will be dependent on whether they chose if they are male or female, it will also need to display their name as entered in the text box.
So far I have the name part working using javascript this is on the front page with the form action directed to a new page:
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
and this is on the other page:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.getElementById("name").innerHTML = mytext;
}
The main problem here is that this always directs to the same page. Can anyone tell me how I could solve this problem and add in the option for a user to choose their gender and the next page would be dependant on this choice?
edit: This is my form
<form class="enter-name" name="myform" onsubmit="tosubmit();" action="page1.html">
<input id="mytext" type="text" name="data" placeholder="Enter name" maxlength="12">
Male: <input type="radio" name="gender" value="male" /><br />
Female: <input type="radio" name="gender" value="female" /><br />
<input id="name-submit" type="submit" value="">
</form>
You can solve this with php - have the form post to a handler that will redirect based on the posted values. In this case the handler is in the same page:
<?php
if(isset($_POST['name'], $_POST['gender'])){
$page = ($_POST['gender']=='male')? 'male-page.php' : 'female-page.php';
header('Location:'.$page.'?name='.$_POST['name']);
die();
}
?>
<html>
<head><!-- head stuff here--></head>
<body>
<form class="enter-name" name="myform" action="" method="post">
<input id="mytext" type="text" name="name" placeholder="Enter name" maxlength="12">
Male: <input type="radio" name="gender" value="male" /><br />
Female: <input type="radio" name="gender" value="female" /><br />
<input id="name-submit" type="submit" value="">
</form>
</body>
</html>
in the redirected to page, you can access name via the query string parameter in php:
<div id="name">
<?php echo $_GET['name'];?>
</div>
Related
sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form
I want to go to different templates(page) whatever is selected(radio button) from a single form. I want to include just one button in my form.
Here as if someone selects template1 I will to page template1.php.
If I select template2 I will go to template2.php.
I have saved the below code as form.php
<form method="POST" action=
"<?php if(($rb = $_POST('template'))=='1'){?>
template1.php
<?php }
if(($rb = $_POST('template'))=='2'){?>
template2.php
<?php } ?>"
enctype="multipart/form-data">
<label>First Name: </label>
<input type="text" name="firstname">
<label>Last Name: </label>
<input type="text" name="lastname">
<input type="radio" value="1" name="template">Template 1
<input type="radio" value="2" name="template">Template 2
<button type="submit" name="upload">POST</button>
</form>
Use JavaScript for this instead. PHP is a server-side language, which means that you have to submit the form to the server before PHP knows which option you selected. JavaScript can deal with this right when you change it instead, as it is a client-side language.
Create an event-listener for a click on the input with the name of template. Then toggle the action accordingly to that.
$("input[name=template]").on("click", function() {
var action = "";
switch($(this).val()) {
case "1":
action = 'template1.php';
break;
case "2":
action = 'template2.php';
break;
}
$(this).parent("form").prop("action", action);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" enctype="multipart/form-data">
<label>First Name: </label>
<input type="text" name="firstname">
<label>Last Name: </label>
<input type="text" name="lastname">
<input type="radio" value="1" name="template">Template 1
<input type="radio" value="2" name="template">Template 2
<button type="submit" name="upload">POST</button>
</form>
I have made a form in my site, which will allow me to get suggestions about Rubik's cube algorithms, but how to know what input the user has? For better understanding, I've given the code below:
<form method="POST">
<label>Your name: </label><br>
<input type="text" name="name" placeholder="Your Name" required><br><br>
<label>Your E-mail: </label><br>
<input type="email" name="email" placeholder="email#domain.com" required><br><br>
<label>Select puzzle: </label><br>
<input type="radio" name="2x2" value="2x2">2x2<br>
<input type="radio" name="3x3" value="3x3">3x3<br><br>
<label>Select set/subset: </label><br>
<input list="set"><br><br>
<datalist id="set">
<option>Ortega OLL</option>
<option>Ortega PBLL</option>
<option>CLL</option>
<option>EG-1</option>
<option>EG-2</option>
<option>F2L</option>
<option>OLL</option>
<option>PLL</option>
<option>COLL</option>
<option>WV</option>
</datalist>
<label>Your Alg: </label><br>
<input type="text" name="alg"><br><br>
<input type="submit" name="submit" class="w3-black w3-button w3-hover-white w3-hover-text-blue w3-text-white">
</form>
Please add action attribute to your form tag and on submit here is the example
<form action="getvalue.php" method="post">
</form>
Note: Every form element must have unique name .
after adding action attribute then create getvalue.php file and add following code in to it
<?php
print_r($_POST);
?>
Above code will give all the form field values
do let me know if it was helpfull...
I'm not sure exactly what you want to do, but here is an example of a form that submits to itself. This will allow you to remain on the same page after the form has been submitted. You can change what the user sees to indicate that the form was done successfully/etc. I have tested this code and it works.
<main>
<?php
// When the form is submitted
if (isset($_POST["submitButton"])){
//Do something with the data from the form - you don't have to print it out.
//This is all done on the server.
//Connect to DATABASE, send an EMAIL, VALIDATE the form, etc.
print("<pre>");
print_r($_POST); // for all GET variables
print("</pre>")
?>
<!-- This HTML will be visible to the user after the form has been submitted. -->
<h1>The form has been submitted successfully!</h1>
<?php
}else{ //If the form has not been submitted
?>
<form method = "post" >
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" id = "submitButton" name = "submitButton" value="Submit">
</form>
<?php
} //End else
?>
</main>
// I apologize for giving the whole code, with omission of the urls, but my code will be returning false just fine, then the next time I try to add a new function, it will no longer return false, and upon removing the new function, it does not return to working again as it did before. I have tried onsubmit=return and onclick=return both.
The other issue is for function combine() in my code. It doesn't ever seem to work, and I have tried numerous different methods. I have tried just alerting with "Test", and the alert doesn't even work.
UPDATED: Now we have it returning false properly for invoices not matching, with alert. It also gives alert for Emails not matching, however it does not return false for emails not matching, and continues to the url. I am showing no errors in the console now. It also does correctly combine and alert to show the invoice and name together.
UPDATE: Now have it working completely. See my final comment below to see how I fixed this last issue. Hope this helps someone!
<!DOCTYPE html>
<!-- // working code except for combining the invoice with the name -->
<head>
<title>INFORMATION FORM</title>
</head>
<!-- // This code compares two fields in a form and submit it -->
<!-- // if they're the same, or not if they're different. -->
<body>
<script type="text/javascript">
function checkInvoice(theform) {
if (theform.invoice1.value != theform.invoice2.value)
{
alert("The INVOICE numbers do not match, please review for mistakes to assure your account gets credited.");
return false;
} else {checkEmail(theform);
}
}
function checkEmail(theform) {
if (theform.EMAIL_1.value != theform.Email.value)
{
alert("The EMAIL addresses you provided do not match. Please correct the EMAIL address and try again.");
return false;
} else {
<!-- // This code combines two fields into the CustRefID-->
function combine()
{
var y=document.getElementById("invoice2").value;
var x=document.getElementById("FName").value;
var InvoiceName = y+""+x;
document.getElementById("CustRefID").value = InvoiceName;
alert(document.getElementById("CustRefID").value);
}
combine(); <!--// this calls the combine function when the email addresses match-->
return true;
}
}
</script>
<form name=theform action= "https://hos###/Index" method ="POST" target="_blank" onsubmit="return checkInvoice(this);" >
<input type="hidden" name="HostedKey" id="HostedKey" value="####" />
<input type="hidden" name="Gateway_ID" id="Gateway_ID" value="#####" />
<input type="hidden" name="IndustryCode" id="IndustryCode" value="2" />
<!-- the next line blank value tells the hosted page to allow the customer to use credit cards as the only allowed payment type. -->
<!-- If you want to only allow more than credit cards, replace “CC” with “” for the value -->
<input type="hidden" name="PaymentType" id="PaymentType" value="CC" />
<!-- the next line allows the hosted page to capture some perhaps useful info to identify the payment. -->
<strong><span style="color: #ff0000;">INVOICE</span></strong> Number: <input type="text" name="invoice1" required id="invoice1" value="" size="40" maxlength="40" />
<br>
Please Confirm your <strong><span style="color: #ff0000;">INVOICE</span></strong> number: <input type="text" name="invoice2" required id="invoice2" value="" size="40" maxlength="40" />
<p>
Patient Full Name (as it appears on your paper bill): <input type="text" name="FName" id="FName" required value="" size="40" maxlength="40" />
<p>
PHONE (###-###-####): <input type="text" pattern="^\d{3}-\d{3}-\d{4}$" name="PhoneNumber" required id="PhoneNumber" value="" />
<p>
<input type="hidden" name="Amount" id="Amount" value="" />
<!-- the next line’s N value tells the hosted page to not display recurring payment fields -->
<input type="hidden" name="RecurringType" id="RecurringType" value="N" />
<input type="hidden" name="RecurringAmount" id="RecurringAmount" value="" />
<!-- the next line defines where users are directed after a successful purchase. It is suggested you create a simple Thankyou page for the site. -->
<input type="hidden" name="RURL" id="RURL" value="http://www.######.com/thankyou/" />
<!-- the next line defines where users are directed after they hit the Cancel button on the TXP Hosted page -->
<input type="hidden" name="CURL" id="CURL" value="http://www.########.com/cancelled/" />
<!-- If AVSRequired equals "Y", Address Line 1 and ZIP Code become required fields on the hosted page -->
<input type="hidden" name="AVSRequired" id="AVSRequired" value="Y"/>
<!-- If CVV2Required is set to "Y", than CVV2 becomes a required field on the hosted page -->
<input type="hidden" name="CVV2Required" id="CVV2Required" value="Y"/>
<!-- If EmailRequired is set to "Y", then Email becomes a required field on the hosted page -->
<input type="hidden" name="EmailRequired" id="EmailRequired" value="Y"/>
<!-- the next line defines enables/disables the ability to receive response data in an POST format. When set to N, no response data is returned to the RURL -->
<input type="hidden" name="PostRspMsg" id="PostRspMsg" value="N"/>
<!-- You can also use a graphic for the button to improve the appearance -->
<p> Enter Your Email Address:<br>
<input type="TEXT" name="EMAIL_1" value="" id=EMAIL_1 required size="40" maxlength="40">
<br>
Please Confirm Your Email Address:
<br>
<input type="TEXT" name="Email" required value= "" size="40" maxlength="40" />
<br>
<input type="hidden" name="CustRefID" id="CustRefID" value="" />
<!-- the next line defines what text is on the button. Replace Submit Payment Now with whatever you desire -->
<p>
<input type="SUBMIT" name="Button" id="Button" value="Make Payment Now" ></p>
</form>
</body>
</html>
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'].