Add multiple fields to form - javascript

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/

Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.

I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );

try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/

It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}

You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)

Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});

This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/

First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

Related

How can I handle duplicate inputs name?

I have a dynamic form which probably has duplicate input names.
$(".add_more_staff").on("click", function(){
var $newMember = $(this).siblings('.company_members').clone();
$newMember.insertBefore($(this));
})
a, input{
display: block;
margin-bottom: 5px;
}
input{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<div class="company_members">
<input class="staff_name" type="text" name="name" required placeholder="name" />
<input class="staff_mobile" type="text" name="mobile" required placeholder="mobile" />
<hr />
</div>
<input type="button" class="add_more_staff" value="Add more staff" />
<input type="submit" value="register_company_staffs" />
</form>
In the code above, you will have two inputs named mobile (or name) if you click on Add more staff button once.
Now I want to know, how should I get it in the PHP codes? According to some tests, $_POST['mobile'] contains the last input value. So how can I get all inputs value in PHP?
Should I make different names for new inputs in jQuery like name="mobile-n" (n = 1, 2 ..)
Should I use array-name for inputs like name="mobile[]" ?
Or what?
Try like this:
<div class="company_members">
<input class="staff_name" type="text" name="name[]" required placeholder="name" />
<input class="staff_mobile" type="text" name="mobile[]" required placeholder="mobile" />
</div>
in PHP:
$staff_names = $_POST['name'];
$staff_mobiles = $_POST['mobile'];
try this with jquery, during appending the html, you can add dynamic increment variable to like
staff_name_1, staff_name_2, staff_mobile_1, staff_mobile_2
with this, you can easily save or define the unique names, like I am showing you on simple example:
var a=0;
$(".add_more_staff").on("click", function(){
$(".company_members").each(function(){
a++;
$(".staff_name").attr('name', $(".staff_name").attr('name')+a);
});
});
Hope you can my idea.
Please try below it will contains data in groups, so you can easily loop it after post data and your JQuery code seems fine.
<div class="company_members">
<input class="staff_name" type="text" name="data[0][name]" required placeholder="name" />
<input class="staff_mobile" type="text" name="data[0][mobile]" required placeholder="mobile" />
</div>
<div class="company_members">
<input class="staff_name" type="text" name="data[1][name]" required placeholder="name" />
<input class="staff_mobile" type="text" name="data[1][mobile]" required placeholder="mobile" />
</div>

Show hidden input javascript/jquery

Why is the hidden form not shown when it looses focus? The alert is coming up nicely when leaving the input but the other hidden form is still not there.
html
<body>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
</body>
javascript
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
alert("This input field has lost its focus.");
$("#validation_message_email").show();
}
You can't display a hidden input like that.A span will suit better for this purpose,
<input type="text" id="myinput" value="">
<span style="display:none" id="validation_message_email">enter a valid email</span>
validation_message_email doesn't have its display style property as none, so show() will not make it visible from type="hidden".
You need to replace
$("#validation_message_email").show();
with
$("#validation_message_email").attr( "type", "text" );
However, if the intent is to only show a message, then you don't need to use a hidden input for the same.
<body>
<input type="text" id="myinput" value="">
</body>
and
window.onload = function() {
$("#myinput").blur(function(){
alert("This input field has lost its focus.");
$(this).append('<span id="emailValidationMessage">enter a valid email</span>')
});
$("#myinput").focus(function(){
$("#emailValidationMessage").remove();
});
};
No need to use type="hidden" as hidden elements are not display:none they are hidden by default.
Use type="text" and hide it with css and show where you want
<input type="text" id="myinput" value="" style="display:none;">
use like this
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">
<script>
window.onload = function() {
$("#myinput").blur(myAlert);
};
function myAlert() {
$("#validation_message_email").attr("type","text");
}
</script>
<div class="form-group" id="usernamediv">
<input class="form-control" name="username" id="username"
placeholder="Username" type="text" required=""> </div>
<div class="form-group" id="passworddiv">
<input name="password" class="form-control" id="password" placeholder="Password" type="password" required="">
</div>
<button id="#loginButton">Login</button>
<button id="#forgotpassword">Forgot Password</button>
<script>
$("#forgotpassword").hide();
$("#forgotpassword").click(function(e){
$("#loginButton").hide();
$("#usernamediv").show();
$("#passworddiv").hide();
})
</script>
Check this jsfiddle link, it might help you.
$("#myinput").blur( function(){
myAlert();
});
function myAlert() {
$("#validation_message_email").attr("type", "text");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input type="text" id="myinput" value="">
<input type="hidden" id="validation_message_email" value="enter a valid email">

Add to cart without refreshing using JavaScript

When I press the add to cart button, data should be inserted into the database and should be displayed immediately above the form without redirecting to the query page. In this code the first form is working correctly, but the next two forms which are duplicates of the first form are not working. The problem is that the next two forms, when submitted, get redirected to the query page. The index page code is:
<html>
<head>
<title>fetch</title>
</head>
<body>
<ul></ul>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<span id="result1"></span>
<script type="text/javascript" src="http://localhost/json/jquery.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script2.js"></script>
</body>
</html>
The query code is:
<?php
include_once('http://loaclhost/json/conn.php');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO users VALUES('$name','$age')"))
echo "successfully";
else
echo "failed";
The JavaScript code is:
$("#sub").click(function(){
$.post($("#myform").attr("action"),$("#myform :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$("#myform").submit(function(){
return false;
});
function clearinput()
{
$("#myform :input").each(function(){
$(this).val('');
});
}
You are submitting form by id : $("#myform").submit(function(){}
and the issue here is that you have given same ids for all the three forms here, make sure that each form will have different id.
also Button ids should be unique
As #asim has mentioned duplicated ids are the problem.try following code.
working js fiddle.http://jsfiddle.net/gw84j7hg/. (Using id selecters)
Updated fiddle using class selecters http://jsfiddle.net/gw84j7hg/2/
Form Code.
<form action="userInfo.php" method="post" id="myform" class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform2"
class="formSelecterClass" >
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub1">save</button>
</form>
<form action="userInfo.php" method="post" id="myform3"
class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub2">save</button>
</form>
<span id="result1"></span>
JS Code
$(".formSubmitButtonClass").click(function(){
$.post($(".formSelecterClass").attr("action"),$(".formSelecterClass :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$(".formSelecterClass").submit(function(){
return false;
});
function clearinput()
{
$(".formSelecterClass :input").each(function(){
$(this).val('');
});
}
ID on single HTML files can not repeated. If repeated, the first ID will work out and rest IDs will be invalid. That's why $("#myform") will only apply to the first form.

how can i check all form element isn't empty on one function?

<form action="surl.php" method="get" id="surl">
<input type="text" placeholder="name of column" name="column_name"/>
<textarea placeholder="description for column name" name="description"></textarea>
<div class="surl"><input type="url" placeholder="first url" name="url1"/></div>
<div class="surl"><input type="url" placeholder="second url" name="url2"/></div>
<div class="surl"><input type="url" placeholder="third url" name="url3"/></div>
<input type="submit" class="surl_submit">
</form>
if one of my input fields or textarea is empty while submit button click, i don't want to post the form.how can i control this form's input and textarea fields at the same time instead of controling one by one?
Call the validation function on click of submit and submit form only when if the all requirements are fullfilled.
DEMO
HTML
<form action="surl.php" method="get" id="surl">
<input id="mytext1" type="text" placeholder="name of column" name="column_name" value="" />
<textarea id="mytext2" placeholder="description for column name" name="description"></textarea>
<div class="surl"><input class="inputUrl" type="url" placeholder="first url" name="url1" value=""/></div>
<div class="surl"><input class="inputUrl" type="url" placeholder="second url" name="url2" value=""/></div>
<div class="surl"><input class="inputUrl" type="url" placeholder="third url" name="url3"/ value=""></div>
<input type="submit" class="surl_submit" onclick="return validateForm()" value="submit">
</form>
SCRIPT
function validateForm(){
var input1 = document.getElementById('mytext1');
var textarea1 = document.getElementById('mytext2');
var allInputs = document.getElementsByClassName('inputUrl');
for(var i=0; i<allInputs.length; i++){
if(!allInputs[i].value){
return false;
}
}
if(!input1.value){
return false;
}else if(!textarea1.value){
return false;
}
}
Add a class to the input/textarea tags, call a function on submit and do something like this:
document.querySelector('.surl_submit').onclick = function(e) {
var input = document.getElementsByClassName('classname');
var i = input.length;
while(i--) {
if(input[i].value == '') {
// you could display some sort of message here
e.preventDefault();
return;
}
}
};
you can add a class for all relevant fields somthing like: "tovalidate" and using jquery:
if ($('.tovalidate').filter(function(){return $(this).val()=='';}).length>0)
//do not submit
else
//submit

How can i make a simple form to calculate quantity x's a fixed rate?

Ok, I have a good understanding of how javascript works, but not how to implement it. I have a simple form that needs to calculate on the fly the price of x number of tickets at 75.00 each. Let's say form id is quantity & total, with 75.00 being a rate. What would be the script to execute this and where should I add it.
The pertinent HTML is this:
<form id="docContainer" enctype="multipart/form-data" method="POST" action=""
novalidate="novalidate" data-form="preview">
<label id="item4_label_0" ># of Tickets</label>
<input type="text" id="quantity" maxlength="254" data-hint="" name="quantity" required/>
<label id="item13_label_0">Price Per Ticket</label>
<input name="item_price" type="text" id="item_price" placeholder="75.00"
maxlength="254" readonly data-hint="75.00"/>
<label id="item14_label_0" >Total</label>
<input name="total_price" type="text" id="total_price" maxlength="254" readonly/>
<input type="submit" class="fb-button-special" id="fb-submit-button" value="Submit" />
</form>
Your inputs don't have ids so I've used their names. This is how you would do it with jQuery. I've forgotten how to write old school javascript, perhaps someone else can add to this.
<script src="jquery.js"></script>
<script>
$(function(){
$('input[name="quantity"]').on('change keyup', function(){
$('input[name="total_price"]').val($(this).val() * $('input[name="item_price"]').val());
});
});
</script>
goes before
</body>
Edit: Added the necessary stuff for jQuery, but this can be done with regular js.
<html>
<head>
<script>
window.onload = function() {
var calculSumToString = function calculSumToString() {
totalField.value = (qtyField.value * itemPriceField.value).toFixed(2) + " $";
};
var totalField = document.getElementById('total_price');
var qtyField = document.getElementById('quantity');
var itemPriceField = document.getElementById('item_price');
qtyField.onkeyup = calculSumToString;
itemPriceField.onkeyup = calculSumToString;
};
</script>
</head>
<body>
<form id="docContainer" enctype="multipart/form-data" method="POST" action=""
novalidate="novalidate" data-form="preview">
<label id="item4_label_0" ># of Tickets</label>
<input type="text" id="quantity" maxlength="254" data-hint="" name="quantity" required/>
<label id="item13_label_0">Price Per Ticket</label>
<input name="item_price" type="text" id="item_price" value="75.00"
maxlength="254" readonly data-hint="75.00"/>
<label id="item14_label_0" >Total</label>
<input name="total_price" type="text" id="total_price" maxlength="254" readonly/>
<input type="submit" class="fb-button-special" id="fb-submit-button" value="Submit" />
</form>
</body>
</html>

Categories

Resources