How do I validate the input(name and age) below? E.g. not allowing empty inputs, maximum age from 0 to 100 and max length? I just started to look into JavaScript/JQuery today.
<form action="#">
<fieldset>
<div class="textinput">
<label for="name">Your name:</label>
<input type="text" name="name">
</div>
<div class="textinput">
<label for="name">Your age:</label>
<input type="text" name="age">
</div>
<div class="textareainput">
<label for="info">About yourself:</label>
<textarea></textarea>
</div>
<div class="action">
<button>Submit</button>
</div>
</fieldset>
</form>
I hope this not a bad question. If it is, please give me the reason for downvote so I can improve my future posts.
I think this is what you want. there are so many libraries (validations) that you can use to validate your script. but if you want do do it in your own way try this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="#">
<fieldset>
<div class="textinput">
<label for="name">Your name:</label>
<input type="text" name="name" id="nameid">
</div>
<div class="textinput">
<label for="name">Your age:</label>
<input type="text" name="age" id="ageid">
</div>
<div class="textareainput">
<label for="info">About yourself:</label>
<textarea id="textareaid"></textarea>
</div>
<h3 style="color:red;font-family:monospace;" id="warning"></h3>
<div class="action">
<input type="button" value="submit" id="click">
</div>
</fieldset>
</form>
</body>
<script type="text/javascript">
$("#click").click(function(){
$("#warning").text("");
var namefield = $("#nameid").val();
var agefield = $("#ageid").val();
var texarefield = $("#textareaid").val();
if (namefield == "" || agefield == "" || texarefield == "")
{
$("#warning").text("all field sholud be fill");
}
else if (namefield != "" && agefield != "" && texarefield != "")
{
var ageInteger = parseInt(agefield);
if (ageInteger < 0 || ageInteger > 100)
{
$("#warning").text("age should be between 0 and 100");
}
else
{
$("#warning").text("");
}
}
else
{
$("#warning").text("");
}
});
</script>
</html>
this is very basic and simple validation.hope this will help to you.
You can use https://jqueryvalidation.org/
The HTML doesn't need to be altered. See https://jqueryvalidation.org/validate/#rules
Related
Please help me, I'm stuck.
Why doesn't the JavaScript below work? The script is checking if phone number and address is empty, but when the phone number and address field is entered, the alert still pops out.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
function checkingIsEmpty() {
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
I'd agree with #Madara's comment, that you should... just add required attribute on form inputs which are required and let the browser do the work for you
However, I believe the reason your code is not working is because you appear to be setting the const values of phone and address on entry to the screen... and then you're checking that initial value (rather than the latest value).
Instead you need to get the latest value from the controls as part of the function...
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value ==''){
alert("Please insert your address");
return false;
}
return true;
}
(Minor edit, you also need to return true at the end of your function, otherwise your submit won't work)
simplest way is to check if (!phoneInput.value) { ... }
as empty string and null will return falsy value
The problem you are having is because you are assigning the value of the fields at the time the page loads. Not at the time the function is called on submit. If you move the variable assignment into the function it should work for you.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
function checkingIsEmpty(){
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
return false;//for the example I don't want it to submit
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
You need to include the document.getElementById in your conditionals. Also, I would wrap both conditionals (Phone and Address) in another conditional so you can add classes for error styling on errored fields.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
var phone = document.getElementById("phoneNumberInput").value;
var address = document.getElementById("addressInput").value;
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == '' || document.getElementById("addressInput").value == '') {
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value == ''){
alert("Please insert your address");
return false;
}
} else {
alert('success');
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
The values of inputs are stored inside a constant, not a variable.
When page is loaded, the script is executed and the contents of actual inputs are stored.
When you're calling checkingIsEmpty() the values aren't refreshed.
I suggest you to get the value inside the checkingIsEmpty() function if you want to keep checking with javascript, but as suggested Madara in comments, you can use the required attribute <input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber" required>.
Checking inputs with required attribute or javascript is nice, but you have to check it server-side too. It's easy to press F12 and edit dom.
function checkingIsEmpty()
{
let phone = document.getElementById("phoneNumberInput").value;
let address = document.getElementById("addressInput").value;
if (phone == '')
{
alert("Please insert your phone number");
return (false);
}
if (address == '')
{
alert("Please insert your address");
return (false);
}
return (true); //You forgot to return true in case of your form is validated
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
here I'm doing contact forms.In the same page, I have 10 forms and I want to validate all form.I want to use same validation code for all forms.here I gave id's but the problem is the same id's not working on the same page.I want to use current id.Can anyone suggest how should I do?
Feel free to tell is there any mistakes in my code.
Thanks
$(document).ready(function(){
/* name*/
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* E-mail */
$('#contact_email').on('input', function() {
var input=$(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email=regex.test(input.val());
if(is_email){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* select People*/
$('#contact_select').change(function() {
var select=$(this);
var selectOption = $("#contact_select option:selected").val();
if(selectOption){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* select Time*/
$('#contact_time').change(function() {
var select=$(this);
var selectTime = $("#contact_time option:selected").val();
if(selectTime){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("#contact_submit button").click(function(event){
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#contact_"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free){
return false;
}
else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row current" id="demo1">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
It seems you are using HTML5, then adding custom methods for validation is not a good idea.
Try using jquery validation and pattern attribute like:
function submitForm(id){
var isValid = $("#" + id).valid();
if(isvalid)
/* Yes valid*/
else
/* Invalid*/
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<div class="row current" id="demo1">
<form id="contact1" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" class="btn" onclick="submitForm('contact1')"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact2" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"/>
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" onclick="submitForm('contact2')" class="btn"> Submit</button>
</div>
</form>
</div>
UPDATE:
Dynamic function called on button clicked. Type is button instead of submit
Hope you will get the point and it helps.
Happy Coding !!!!
You can use a custom attribute like data-validation="validation-type" on your input controls then do a for each on your form with
$('<myform>').find('*[data-validation]').each(function(){
// in here get the this object for each input control the code to validate comes here
var valType = $(this).attr('data-validation');
switch(valType)
{
case 1:
//validation of case 1
break;
//add other cases as of your need.
}
});
Edit 1
For example you can play around with this snippet:
var button = $("button")
// handle click and add class
button.on("click", function() {
//validating controls for form 1
debugger;
$('#myform1').find('*[data-validation]').each(function(e) {
validateInput(this);
});
//validating controls for form 2
$('#myform2').find('*[data-validation]').each(function(e) {
validateInput(this);
});
})
function validateInput(control) {
if (control == null || control === undefined)
return null;
var validType = $(control).attr('data-validation');
if (validType == null || validType === undefined)
return null;
switch (validType) {
case "text":
if ($(control).val().trim().length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
case "number":
debugger;
var value = $(control).val().trim();
if (isNaN(value) || value.length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
}
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
.valid {
border: 2px solid green;
}
.invalid {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
Form 1
</h4>
<form id="myform1">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<h4>
Form 2
</h4>
<form id="myform2">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<button>
Click me to validate
</button>
When I call the index.js it doesn't work in my webhost server and the cdn too but works perfectly on my Local xampp server .
<?php
/* Main page with two forms: sign up and log in */
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign-Up/Login Form</title>
<?php include 'css/css.html'; ?>
</head>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['login'])) { //user logging in
require 'login.php';
}
elseif (isset($_POST['register'])) { //user registering
require 'register.php';
}
}
?>
<body>
<div class="form">
<ul class="tab-group">
<li class="tab">Sign Up</li>
<li class="tab active">Log in</li>
</ul>
<div class="tab-content">
<div id="login">
<h1>Welcome to </h1>
<form action="index.php" method="post" autocomplete="off">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" required autocomplete="off"
name="email"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" required autocomplete="off"
name="password"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" name="login" />Log
In</button>
</form>
</div>
<div id="signup">
<h1>Sign Up for Free</h1>
<form action="index.php" method="post" id="form1"
autocomplete="off">
<div class="top-row">
<div class="field-wrap">
<label>
First Name<span class="req">*</span>
</label>
<input type="text" required autocomplete="off"
name='firstname' id="txtNumeric" />
</div>
<div class="field-wrap">
<label>
Last Name<span class="req">*</span>
</label>
<input type="text"required autocomplete="off"
name='lastname'
id="txtNumeric" />
</div>
</div>
<div class="field-wrap">
<label>
Contact number<span class="req">*</span>
</label>
<input type="number"required autocomplete="off"
name='contact'
onclick="return AllowSingleSpaceNotInFirstAndLast();" />
</div>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email"required autocomplete="off" name='email'
onclick="return AllowSingleSpaceNotInFirstAndLast();" />
</div>
<div class="field-wrap">
<label>
Set A Password<span class="req">*</span>
</label>
<input type="password"required autocomplete="off"
name='password'/>
</div>
<button type="submit" class="button button-block"
name="register"
onclick="return validates()" />Register</button>
</form>
</div>
</div><!-- tab-content -->
</div> <!-- /form -->
<script
src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'>
</script>
<script src="js/index.js"></script>
<script type="text/javascript">
function validates(){
$(function() {
$('#txtNumeric').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key
<=
40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
function AllowSingleSpaceNotInFirstAndLast() {
var obj = document.getElementById('TextBox1');
obj.value = obj.value.replace(/^\s+|\s+$/g, "");
var CharArray = obj.value.split(" ");
if (CharArray.length > 2) {
alert("User name NOT VALID");
return false;
}[enter image description here][1]
else {
alert("User name VALID");
}
return true;
}
}
</script>
</body>
</html>
The problem here is I cannot run the code properly in my webhost. My code works fine on local xampp server. I also edited the DB user, DB name etc but it doesn't help. can anyone help me ?
Thank you!
PS. I am new to stackoverflow. sorry for my bad formatting
I think problem is in your path of files you should check your path of file
or may be you had not uploaded your all files with proper code on server.
Replace this code
<script src="js/index.js"></script>
To
<script src="<?php echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>/js/index.js"></script>
I have a very noob question, I have a form with input fields. The form has 10 fields, and the user needs to enter from 1-3 (one being most preferred, to 3 being last choice). After 3 have been filled, I want to either disable all other fields, or just disallow any further input and give an error.
I've got the counting up working, but i can't restrict or pop an error.
here's the code,
jQuery(document).ready(function($){
$("#choices").on('keyup change', function() {
var maxAllowed = 3;
var number = 0;
$(this).find('input, textarea').each(function () {
//if (number < maxAllowed && this.value !== '')
if (this.value !== '')
{
$('.input_count').val(number++);
}
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<form method="post" id="userForm" role="form">
<h3>Selection form</h3>
<p>Fill in your choices from 1-3 (please select only three).</p>
<div id="choices">
<div class="form-group">
<label for="Recreational fishing">Recreational fishing</label>
<input type="text" value="" size="3" name="form[Recreational fishing]" id="Recreational fishing" class="form-control" />
</div>
<div class="form-group">
<label for="Recreational boating">Recreational boating</label>
<input type="text" value="" size="3" name="form[Recreational boating]" id="Recreational boating" class="form-control" />
</div>
<div class="form-group">
<label for="Sightseeing tourist">Sightseeing tourist</label>
<input type="text" value="" size="3" name="form[Sightseeing tourist]" id="Sightseeing tourist" class="form-control" />
</div>
<div class="form-group">
<label for="Exercise">Exercise</label>
<input type="text" value="" size="3" name="form[Exercise]" id="Exercise" class="form-control" />
</div>
<div class="form-group">
<label for="Picnics BBQ">Picnics/BBQ</label>
<input type="text" value="" size="3" name="form[Picnics BBQ]" id="Picnics BBQ" class="form-control" />
</div>
<div class="form-group">
<label for="Sunsets and socialising">Sunsets and socialising</label>
<input type="text" value="" size="3" name="form[Sunsets and socialising]" id="Sunsets and socialising" class="form-control" />
</div>
<div class="form-group">
<label for="Bird watching">Bird watching</label>
<input type="text" value="" size="3" name="form[Bird watching]" id="Bird watching" class="form-control" />
</div>
<div class="alert alert-info">
<div class="form-group">
<label for="counter">Counter:</label>
<input class="input_count form-control" type="text" id="counter" value="">
</div>
</div>
</div>
<input type="submit" value="Submit" name="form[Submit]" id="Submit" class="btn btn-primary btn-block">
</form>
</div>
</div>
.... or here's a fiddle.
http://jsfiddle.net/Flocktome/wmdnnm4j/
any thoughts would be really appreciated. Thanks in advance.
jQuery(document).ready(function($){
$("#choices").on('keyup change', function() {
var maxAllowed = 4;
var number_done = 0;
$(this).find('input, textarea').removeAttr('disabled');
$(this).find('input, textarea').each(function () {
//if (number < maxAllowed && this.value !== '')
if (this.value !== '')
{
$('.input_count').val(++number_done);
}
});
if( number_done >= maxAllowed){
$(this).find('input,textarea').filter(function(){
if($(this).val()== '')
return true;
return false;
}).attr('disabled', 'disabled');
}
});
});
Here the max allowed is set to 4.because of you counter field.Which should be ingnored i think for the test purpose.Once this field is removed the maxallwoed can be set as 3
Try this code. I have found number of fields filled using filter function and disabled other fields using each, when the maximum number of fields allowed are filled. JSFiddle
jQuery(document).ready(function($){
$("#choices").on('keyup', function() {
var maxAllowed = 3;
var els = $(this).find('input, textarea');
var elsFilled = els.filter(function(i,el){ return el.value!="" }).length;
if(elsFilled==maxAllowed)
els.each(function(i,el){ if(el.value=="") el.disabled = true; });
else
els.each(function(i,el){ if(el.value=="") el.disabled = false; });
});
});
This is my code
<!DOCTYPE html>
<html>
<head>
<title>Certificate Generator</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
#main .my-form form .text-box .add-box strong {
font-size: 36px;
}
-->
</style>
</head>
<body>
<div id="main">
<h1 align="center">Certificate Generator</h1>
<div class="type">
<form name="class" action="generate.php" method="post">
<input type="checkbox" name="class" value="i">IL<br>
<input type="checkbox" name="class" value="u">UT</br>
</div>
<div class="my-form">
<form action ="generate.php"role="form" method="post">
<label for="text">Date <span class="box-number"</span></label>
<input type="text" name="date" /></p>
<p class="text-box">
<label for="box1">Student <span class="box-number">1</span></label>
<input type="text" name="students[]" value="" id="box1" />
<a class="add-box" href="#"><strong>Add More Students</strong></a>
</p>
<p>
<input type="submit" value="Generate Certificates" />
</p>
</form>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var n = $('.text-box').length + 1;
if( 250 < n ) {
alert('Maximum Amount of Students');
return false;
}
var box_html = $('<p class="text-box"><label for="box' + n + '">Student <span class="box-number">' + n + '</span></label> <input type="text" name="students[]" value="" id="box' + n + '" /> Remove</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
When I hit submit, the php only gets the first value of the array
$students = ($_POST["students"]);
this is my php for that form, I don't know why it is only returning the first value of the array, this is my first time using forms with JavaScript so it might just be a simple error, I'm not sure
This is your problem:
<form name="class" action="generate.php" method="post">
<input type="checkbox" name="class" value="i">IL<br>
<input type="checkbox" name="class" value="u">UT</br>
</div>
<div class="my-form">
<form action ="generate.php"role="form" method="post">
You are closing your form prematurely because of the closing </div> and then opening a new form.
Your html is invalid and the browser tries to make sense of it, causing your students[] elements to be outside of your form so they never get posted.
The results may vary per browser (tested in Firefox), but validating your html should solve your problem.
Ok, I found the error. I have this working. You are not adding the new elements inside of your form. I rearranged the HTML as the following.
<form name="class" action="generate.php" method="post">
<div id="main">
<h1 align="center">Certificate Generator</h1>
<div class="type">
<input type="checkbox" name="class" value="i">IL<br>
<input type="checkbox" name="class" value="u">UT</br>
</div>
<div class="my-form">
<form action ="generate.php"role="form" method="post">
<label for="text">Date <span class="box-number"</span></label>
<input type="text" name="date" />
</p>
<p class="text-box">
<label for="box1">Student <span class="box-number">1</span></label>
<input type="text" name="students[]" value="" id="box1" />
<a class="add-box" href="#"><strong>Add More Students</strong></a> </p>
<p>
<input type="submit" value="Generate Certificates" />
</p>
</div>
</div>
</form>
Just to clarify, I moved the opening tag of the form outside of your "main" div, and then I closed the form after the "main" div's closing tag. No other changes.