I'm creating a simple form that allows you to enter data that will then be sent to a DB. In particular I need to know from you how I can create a dynamic form that allows me to enter a number of people specified by the user. Basically if the user wants to add 3 people must present 3 new fields to enter Name, Surname and email, if he wants to add 5, 5 new fields.
I write this, but in my index.php it doesn't work.
// Funzione che permette di aggiungere elementi al form (in questo caso rate)
function Aggiungipersone(person) {
var numero_persone = person.value;
var box = document.getElementById('box_person');
if (numero_persone == "") {
box.innerHTML = '';
} else {
if (isNaN(numero_persone) == true) {
box.innerHTML = '';
} else {
var righe = "";
// Inserisco una riga ad ogni ciclo
for (i = 1; i <= numero_persone; i++) {
righe = righe + "Persona n°" + i + " : <input type='text' name='iname" + i + " size='10' value='" + Cognome + "' type='text' name='isurname' size='10' value=''/><br/>";
}
// Aggiorno il contenuto del box che conterrà gli elementi aggiunti
box.innerHTML = righe;
}
}
}
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br> Nome:
<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br> Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
UPDATE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="utils.js"></script>
</head>
<body>
<?php
$( document ).ready(function() {
$("#add").click(function(){
var val1 =$("#n1").val();
for(var i=0;i<val1;i++){
$("#start").append($("#first").clone());
}
});
});
?>
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nome:<input type="text" name="name" size="20"><br>
Cognome:<input type="text" name="surname" size="20"><br>
Email: <input type="email" name="email" size="20"><br>
Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
</body>
</html>
In the utilis.js i inserted:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br>
<br>
</div>
</div>
// content of external javascript file:
$(document).ready(function() {
$("#add").click(function(e) {
e.preventDefault(); // stop the link
var val1 = $("#n1").val();
for (var i = 0; i < val1; i++) {
$("#start").append($("#first").clone());
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- here is the external file -->
<script src="utils.js"></script>
</head>
<body>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name[]" size="20"><br> Cognome:
<input type="text" name="surname[]" size="20"><br> Email: <input type="email" name="email[]" size="20"><br>
<br>
</div>
</div>
</body>
</html>
once you submit form then you will get array into php file and you can access like this
if($_POST['name']){ foreach($_POST['name'] as $name) { echo $name; } }
1) With VueJS - demo on code pen
2) JQuery
const tmpl = $('#tmpl').html().trim()
$('#btn-add').click(() => {
let peopleCount = +$('#people-count').val(),
html = Array(peopleCount)
.fill(tmpl)
.join('')
$('#form-items').append(html)
})
$('#form')
.submit(() => {
alert('Submit form by ajax or remove this mathod for default behavior')
return false;
})
.delegate('.btn-del', {
click() {
$(this).closest('.row').remove()
},
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
you will need something like this:
$("#people").on("keyup", function() {
$("#form").html(""); // clear the form
var people = $(this).val();
for(i=1;i<=people;i++) {
$("#form").append("<input type='text' name='name[]' placeholder='Name Person "+i+"'><br>");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Number of People:</label>
<input type="number" id="people">
<div id="form"></div>
as you see the input names are with [] which means they are arrays.. That means on your server side script you will recieve an array where you have to go through via
foreach($_POST["names"] as $name) {
// do whatever
}
Related
I have in HTML, three input fields and one button.
beneath each input I have a span.
Every click on the button triggers a function in which colors the empty field in red,
How can I insert a text to the span beneath the input in case the empty field?
HTML:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<div class="container">
<label for="firstName">First Name</label>
<input type="text" name="" id="firstName">
<span ></span>
<label for="lastName">Last Name</label>
<input type="text" name="" id="lastName">
<span ></span>
<label for="email">Email</label>
<input type="email" name="" id="email">
<span></span>
</div>
<button onclick="showError()"> Show</button>
<script src="train.js"></script>
</body>
</html>
JS
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
let rowsAreFilled = true
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}
You can have the browser enforce required fields for you in a <form> element with the required attribute:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button> Show</button>
</form>
<script src="train.js"></script>
</body>
You can style the :required and :invalid pseudo classes:
input:required {
placeholder: 'required';
border: 2px solid black;
}
input:invalid:focus {
border: 2px solid red;
background-color: #f004;
}
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button>Show</button>
</form>
<script src="train.js"></script>
</body>
Ok, so the answers above of the kind people didn't really answer the question, I asked how to add a text to the specific span by JavaScript in case of empty field..
Any, this is the answer I got to:
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
const errorOneSpan = document.getElementById("errorOne");
const errorSecSpan = document.getElementById("errorSec");
const errorthreeSpan = document.getElementById("errorthree");
let rowsAreFilled = true
let arrayOfSpans = [errorOneSpan, errorSecSpan, errorthreeSpan ]
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
arrayOfSpans[i].innerText = "Error!"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
arrayOfSpans[i].innerText = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}
I have a form that is simply a input with a zip code and a submit button.
I need some help on submitting the form according to the data inserted.
For example if someone inserts a number between 1000-000 and 2999-999 it will be forward to landing1.html, if the input is between 3000-000 to 4000-999 it will forward to landing2.html and so on.
This is a draft of my code my code for better understanding
$(document).ready(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
Hope someone can help me.
Many thanks!
Like this
We can make it more complex if you have many sets of post codes
$(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
$(".needs-validation").on("submit",function() {
const cp = this.cp.value;
if (cp >= "1000-000" && cp <= "2999-999") this.action = "landing1.html";
else if (cp >= "3000-000" && cp <= "4000-999") this.action = "landing2.html";
// else this.action = "outofrange.html";
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
This is my first time with javascript. I'm making a basic login page where there is a control for the email input. I would like to put an error message of some kind when someone gives an email address with illegal symbol. Here my code:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
</head>
<body>
<div>
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var result = email.search("/[^(a-z | A-Z | 0-9 | #)]/");
if(result !== -1)
{
emailObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
</html>
I have a function I use to validate email addresses, it uses regex. I would suggest jQuery just to show/hide the error message.
function validEmail(val){
if(val.length < 6 || val.length > 255) return false;
return new RegExp(/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/).test(val);
}
$(function(){
$("#email").on("change", function(){
var email = $("#email").val();
if(!validEmail(email)){
$("#emailError").show();
} else {
$("#emailError").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<!-- Some Inputs here -->
<span id='emailError' style='display: none;'>Please enter a valid email address</span><br>
<input type='email' id='email' name='email' placeholder='Email Address' />
<!-- More Inputs here -->
<button type='submit'>Submit</button>
</form>
you're trying to append something to an input element (email input, in this case). I'd suggest to append it to your main div, which in this case I have identified as "YOUR_ID".
Also, I suggest you a more efficint way to check a valid email.
follow the below example
<body>
<div id="YOUR_ID">
<form action="Home.html" method="post">
<label for="id">Username</label>
<input type="text" name="id" id="id" value="" />
<br/>
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value="" />
<br/>
<label for="email">Email</label>
<input type="email" name="email" id="email" value="" />
<br/>
<script type="text/javascript">
function checkEmail ()
{
var emailObject = document.getElementById("email");
var divObject = document.getElementById("YOUR_ID");
var email = emailObject.getAttribute("value").toString();
var error = document.createTextNode("Uncorrect email");
var check = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var result = check.test(email);
if(result !== -1)
{
divObject.appendChild(error);
}
}
</script>
<button type="button" onclick="checkEmail()"> Confirm </button>
</form>
</div>
</body>
Sorry if questions like this get really annoying; I've tried to figure this out without bothering anyone, but I'm a beginner and I'm totally stumped. Here's what I have so far. I want to pull data from the form called "paymentform" and generate a JSON list that I can post in a REST call. My boss wants me to do this specifically with JavaScript rather than jQuery. How would I do that?
function toggleVisibility(id) {
var e = document.getElementById(id);
if (id == "creditCard") {
document.getElementById("creditCard").checked = true;
document.getElementById("eCheck").checked = false;
if (document.getElementById("cardinfo").style.display == "none") {
document.getElementById("cardinfo").style.display = "block";
document.getElementById("bankinfo").style.display = "none";
document.getElementById("cardnumberid").setAttribute("required", true);
document.getElementById("expdateid").setAttribute("required", true);
document.getElementById("cvvnumberid").setAttribute("required", true);
document.getElementById("accountnameid").removeAttribute("required");
document.getElementById("routingnumberid").removeAttribute("required");
document.getElementById("banknameid").removeAttribute("required");
document.getElementById("accountnumberid").removeAttribute("required");
}
}
if (id == "eCheck") {
document.getElementById("creditCard").checked = false;
document.getElementById("eCheck").checked = true;
if (document.getElementById("bankinfo").style.display == "none") {
document.getElementById("cardinfo").style.display = "none";
document.getElementById("bankinfo").style.display = "block";
document.getElementById("cardnumberid").removeAttribute("required");
document.getElementById("expdateid").removeAttribute("required");
document.getElementById("cvvnumberid").removeAttribute("required");
document.getElementById("accountnameid").setAttribute("required", true);
document.getElementById("routingnumberid").setAttribute("required", true);
document.getElementById("banknameid").setAttribute("required", true);
document.getElementById("accountnumberid").setAttribute("required", true);
}
}
}
function setValue() {
document.getElementById("creditCard").checked = true;
document.getElementById("eCheck").checked = false;
document.getElementById("cardinfo").style.display = "block";
document.getElementById("bankinfo").style.display = "none";
document.getElementById("cardnumberid").setAttribute("required", true);
document.getElementById("expdateid").setAttribute("required", true);
document.getElementById("cvvnumberid").setAttribute("required", true);
document.getElementById("accountnameid").removeAttribute("required");
document.getElementById("routingnumberid").removeAttribute("required");
document.getElementById("banknameid").removeAttribute("required");
document.getElementById("accountnumberid").removeAttribute("required");
}
function submitForm() {
var myForm = document.getElementsByName("paymentform")[0];
}
body {
margin-top: 100px;
margin-left: 200px;
margin-right: 350px;
font-family: Helvetica;
font-size: 90%;
}
h1 {
font-family: Helvetica;
font-size: 150%;
}
h2 {
font-family: Helvetica;
font-size: 110%;
}
p {
font-family: Helvetica;
}
<!DOCTYPE html>
<html>
<head>
<title>Payment Information</title>
<link rel="stylesheet" type="text/css" href="CreditCardAndECheckTest.css">
<script src="CreditCardAndECheckTest.js"></script>
</head>
<body onload="setValue()">
<h1>Payment Profile</h1>
<hr>
<p>Enter the information for each field listed below.</p>
<h2>Billing Information</h2>
<form name="paymentform" onsubmit="return window.submitForm()" method="post">
First Name:
<input type="text" name="firstname" required> Last Name:
<input type="text" name="lastname" required>
<br>
<br>Company Name:
<input size="83px" type="text" name="companyname" required>
<br>
<br>Address 1:
<input size=T "30px" type="text" name="address1" required>
<br>
<br>Address 2:
<input size="30px" type="text" name="address2" required>
<br>
<br>City:
<input type="text" name="cityname" required> State/Province:
<input type="text" name="statename" required>
<br>
<br>Zip/Postal Code:
<input size="5px" type="text" name="zippostalcode" required> Country:
<input type="text" name="country" required>
<br>
<br>Email:
<input type="text" name="email" required> Phone:
<input type="text" name="phonenumber" required> Fax:
<input type="text" name="faxnumber">
<br>
<h2>Payment Information</h2>
Payment Type
<input id="creditCard" onclick="toggleVisibility('creditCard')" checked type="radio" />Credit Card
<input id="eCheck" onclick="toggleVisibility('eCheck')" type="radio" />Bank Account
<br>
<br>
<div id="cardinfo" style="display:block">
Accepted Methods: American Express, Discover, JCB, Mastercard, Visa
<br>
<br>Card Number:
<input id="cardnumberid" type="text" name="cardnumber" required>
<br>
<br>Expiration Date:
<input id="expdateid" type="text" name="expdate" required>(mmyy)
<br>
<br>CVV (3-digit number on the back of the card, if applicable):
<input id="cvvnumberid" type="text" name="cvvnumber" required>
</div>
<div id="bankinfo" style="display:none">
Name on Account:
<input id="accountnameid" size="30px" type="text" name="accountname" required> Account Type:
<select>
<option value="checking">Checking</option>
<option value="savings">Savings</option>
<option value="businesschecking">Business Checking</option>
</select>
<br>
<br>9-digit Routing Number:
<input id="routingnumberid" type="text" name="routingnumber" required> Account Number:
<input id="accountnumberid" type="text" name="accountnumber" required>
<br>
<br>Bank Name:
<input id="banknameid" size="30px" type="text" name="bankname" required>
</div>
<br>
<center>
<input type="submit" value="Submit">
</center>
</form>
</body>
</html>
tl;dr: I've provided a jsBin with a working example of your code
So, first off, jQuery exists to normalize odd browser behavior (mostly combatting IE problems) and to provide shorthand ways of doing common things. Writing out document.getElementById() a bunch of times is both tiring and unreadable. I added this simple function to make that particular bit easier:
function byId(element) {
return document.getElementById(element);
}
byId('firstname') // <input type="text" id="firstname" required>
I also changed all your name attributes to IDs. Calling getElementsByNames() is a bit wonky behavior so I personally would avoid it.
Finally, here is how to set the data to pass in a POST request (or whatever).
function submitForm() {
var cardId = byId("cardinfo");
var payment = {};
var data = {};
if (getCSS(cardId, 'display') == "block") {
payment = {
num: byId("cardnumberid").value,
exp: byId("expdateid").value,
cvv: byId("cvvnumberid").value
};
} else {
payment = {
accountName: byId("accountnameid").value,
routingNum: byId("routingnumberid").value,
bankName: byId("banknameid").value,
accountNum: byId("accountnumberid").value
};
}
data = {
first: byId('firstname').value,
last: byId('lastname').value,
company: byId('companyname').value,
addr1: byId('address1').value,
addr2: byId('address1').value,
city: byId('cityname').value,
state: byId('statename').value,
zip: byId('zippostalcode').value,
country: byId('country').value,
email: byId('email').value,
phone: byId('phonenumber').value,
fax: byId('faxnumber').value,
payment: payment
};
data = JSON.stringify(data);
console.log(data);
// Prevent the form from submitting and refreshing the page
return false;
}
You need to create the object you want to send one way or another and then you need to call JSON.stringify(objectName) on it. That will turn the object into a simple string. When you get data back from a request you'll often have to call JSON.parse(objectName) in order to manipulate the data.
Oh, extra credit:
Calling this doesnt work:
if (document.getElementById("bankinfo").style.display == "none") {...
document.getElementById().style only sets style. I created the following wee function to help:
function getCSS(element, attr) {
return window.getComputedStyle(element).getPropertyValue(attr);
}
Take a look at MDN's documentation on getPropertyValue() for more info
I am trying to show forms according to user input in the text box but it is showing it one time only...please help...
index.html:
<html>
<head>
<script type="text/javascript" src="demo1.js"></script>
</head>
<body>
<form name="su">
<input type="text" name="tt" onkeyup="javascript:toggleFormVisibility();" id="sub"/> </a>
</form>
<form id="subscribe_frm" style="display:none">
NAME:<input type="text" name="text">
EMAIL:<input type="text" name="text">
PASSWORD:<input type="text" name="text">
</form>
demo.js:
function toggleFormVisibility()
{
var txt = document.getElementById('sub').value;
for(var i=0;i<txt;i++)
{
var frm_element = document.getElementById('subscribe_frm');
var vis = frm_element.style;
vis.display = 'block';
}
}
A bit of a guess, but I think you are trying to create multiple copies of your form. Try this out:
http://jsfiddle.net/QnrM9/
JS
function toggleFormVisibility() {
var txt = document.getElementById('sub').value;
var neededChildren = txt.length - document.getElementById('form_container').children.length + 1;
for (var i = 0; i < neededChildren; i++) {
var frm_element = document.getElementById('subscribe_frm').cloneNode(true);
var vis = frm_element.style;
vis['display'] = 'block';
document.getElementById("form_container").appendChild(frm_element);
}
}
document.getElementById('sub').addEventListener('keyup', toggleFormVisibility);
HTML
<form name="su">
<input type="text" name="tt" id="sub" />
</form>
<div id="form_container">
<form id="subscribe_frm" style="display:none">NAME:
<input type="text" name="text" />EMAIL:
<input type="text" name="text" />PASSWORD:
<input type="text" name="text" />
</form>
</div>