How to add a new textfield on clicking a button? - javascript

I'm trying to insert certain sentences to MySQL database using PHP. But the design of the field is such a way that it shows only one field and a [add] button to insert a new textfield. So depending on the user needs, the number of textfields varies.
<div class="row">
<h5>LEARNING GOALS</h5>
<div style="display:table; width:100%;">
<div style="display:table-row;">
<div style="display:table-cell;">
<input class="text-field" name="goal" type="text" placeholder="Goals*" style="width:100%">
</div>
<div style="display:table-cell; vertical-align:middle;width:65px;">
<input class="add-field-btn" type="button" value="+" style="width:65px;"></div>
</div>
</div>
</div>
How can I add a new textfiled and assign name value and when I click on the submit button, to save all the textfield values into the database?

<html>
<head>
<title>jQuery add / remove</title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove </h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>

First of all use your text field name as a array so when user will add new text field you can get all of them in just one post variable and you can store them in different row or as you want.
Now on click on you button append text field with same name as
your first field code:<input class="text-field" name="goal[]" type="text" placeholder="Goals*" style="width:100%">
Javascript code: $('#yourselector').append('<input class="text-field" name="goal[]" type="text" placeholder="Goals*" style="width:100%">');
It the server end you can get all the posted values in $_POST['goal'] which will be a array;

Demo Check this fiddle.
document.getElementById('#whereToAppend').append('<input type="text" name="WhateverYouwant"/>');
document.getElementsByTagName('body')[0].appendChild('<input type="text"/>');
If you want dynamic names, set a class name or id to the input. And make use of setAttribute in javascript to set the name

One solution would be to try and serialize all the inputs and save them to the database. You just send them by submitting the form then in PHP do something like:
$inputs = serialize($_GET); // $inputs = serialize($_POST);
mysql_query('INSERT INTO `table` SET inputs = "'.$inputs.'"'); // try to validate the variable before
This would be nice given the fact that you have variable number of fields.
When you select them use deserialize to recreate the data:
$r = mysql_query('SELECT inputs FROM `table`');
...
$data = deserialize($row['inputs']);
Another option would be to get all the inputs with JavaScript or jQuery and pass them via AJAX.
var _data = [];
$('input.text-field').each(function(i, e) {
_data.push($(e).val());
});
$.post('file.php', { d : JSON.stringify(_data)}, function(e){
alert(e);
})
PHP:
$d = json_decode($_POST['d']);
foreach($d as $k => $v) {
// value of the input no. $k is $v
}
You can use #Nickunj's jQuery code for appending the new input.

Related

Display one text field on click from a set number of text fields

I have a form where users have 10 text fields. But initially only 1 text field is shown. If the user needs to enter more data they can click on the add one button and then displays the next text field from the maximum of 10.
like so:
Im working with angular.js so I thought about using ng-show to hide & show fields.
<div class="form-group">
<input type="text" class="form-control" name="pointOne" ng-show="pointOne">
<input type="text" class="form-control" name="pointTwo" ng-show="pointTwo">
<input type="text" class="form-control" name="pointThree" ng-show="pointThree">
<span><button ng-click="addOne()">Add One</button></span>
</div>
I am unable to figure out the most effective way to doing this. Any hints, help or suggestions would be great.
Haven't tested it but this is how I would do it:
<div class="form-group" >
<input ng-repeat="i in getNumber(number)" type="text" class="form-control" name="point{{i}}" ng-show="$index<=counter">
<span><button ng-click="addOne()">Add One</button></span>
</div>
And in your controller just add something like this:
$scope.number = 10;
$scope.getNumber = function(num) {
return new Array(num);
}
$scope.counter=0;
$scope.addOne= function() {
$scope.counter++;
}
You could easily add elements to the DOM:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});
To go the Angular route, I'd suggest using ng-repeat. Here's a fiddle that might not be exactly what you're looking for, but it shows how to use ng-repeat and you can modify as needed:
Fiddle: https://jsfiddle.net/jvsnao97/5/
<body ng-app="myApp" ng-controller="myController">
<button ng-click="add_input()">Add Input</button>
<br/><br/>
<input type="text" class="form-control" ng-repeat="x in random_array" name="point{{$index}}">
</body>
var app = angular.module("myApp", []);
app.controller("myController", ["$scope", function($scope) {
$scope.random_array = [0]
$scope.add_input = function() {
var i = $scope.random_array.length
$scope.random_array.push(i)
}
}]);
When you want a new <input>, you simply push a new element to $scope.random_array.
Probably good way is to make array of input fields and then ng-repeat them. When user clicks on AddOne, then just push input field in array, and it will be there.
<html>
<head>
<title>jQuery add / remove textbox</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
JQuery can be used to add inputs in your addOne() method.
Like so:
var maxInputs = 10;
var currentInput = 0;
function addOne() {
currentInput++;
if (currentInput > maxInputs) {
currentInput = maxInputs;
return;
}
var name = "point" + currentInput;
var $input = $("<input type='text' class='form-control' name='" + name + "' ng-show='" + name + "'>");
$(".form-group").append($input);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<span><button onclick="addOne()">Add One</button></span>
</div>

jquery create dynamic div inside div

I have created Dynamic insert using JQuery. now I can not able to create dynamic div inside div this is my code snippet
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'form-group' + counter)
.attr("class", 'form-group' );
var newTextBoxDiv1 = $(document.createElement('div'))
.attr("id", 'col' + counter)
.attr("class", 'col-md-8' );
newTextBoxDiv.after().html('<label class="col-md-3 control-label">Achievement #'+ counter + ' : </label>');
newTextBoxDiv1.after().html(
'<input type="text" name="achievement' + counter +
'" id="achievement' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv1.appendTo("#TextBoxesGroup")
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#form-group" + counter).remove();
$("#achievement" + counter).remove();
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="form-group1">
<label class="col-md-3 control-label">Achievement #1 : </label><input type='textbox' name="achievement" id='achievement' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
</body>
</html>
that create Dynamic Div like this
<div id="col2" class="col-md-8"><input type="text" value="" id="achievement2" name="achievement2"></div>
<div id="form-group3" class="form-group"><label class="col-md-3 control-label">Achievement #3 : </label></div>
but I want to append div that means div inside div and the code should be like this
<div id="col2" class="col-md-8"><input type="text" value="" id="achievement2" name="achievement2">
<div id="form-group3" class="form-group"><label class="col-md-3 control-label">Achievement #3 : </label></div></div>
newTextBoxDiv1.appendTo("#col2")
Demo
Jquery
$('#idd').click(function() {
$( this ).append("<div >new div</div>");
});
Html
<div id="idd">
Contgert
</div>
Set the innerHTML of the outer div to contain the HTML for the inner div.
This way you can dynamically generate all the different internal divs you want depending on the situation.

add input fields dynamically with codeigniter

I'm trying to add dynamically input fields in Codeigniter when the user clicks the link but it doesn't seem to work. It will be really helpful if someone can figure it out.
My JS code is:
<script src="js/jquery.js" type="text/javascript">
var count = 1;
jQuery(document).ready(function() {
$('p#add_field').click(function(){
count += 1;
$('#language').append(
'<strong>Language #' + count + '</strong><br />'
+ '<input id="language' + count + '"name="languages[]' + '" type="text" /><br />' );\
});
});
</script>
And my form code is:
<div id="container">
some code
<div id="body">
some more code
<div id="language">
<p id="add_field">Προσθηκη Γλώσσας</p>
</div>
</div>
</div>
var count = 1;
$('p#add_field').click(function(){
count += 1;
var html='<strong>Language #'+ count +'</strong><br />'+'<input id="language'+ count +'"name="languages[]'+'" type="text" /><br />';
$('#language').prepend(html);
});
remove all the spaces in appending html . javascript gives Unterminated String literal errors
fiddle

Jquery - dynamically added input field doesn't send value to post

I have this particular jquery code to add/remove fields on a form and then send its values:
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#reglas div").length + 1;
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');
var fName = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fName2 = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fName2);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function() {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
In which you can add/remove fields on the Cache section but the form sends every value except those which were added dynamically.
How can I solve it? You can see the posted form data with Firebug.
Here is a JS Fiddle for you: http://jsfiddle.net/34rYv/121/
Also I realized that when I delete fields, its name doesn't rename.
Maybe you can help me with this too :)
Thanks in advance
Nicolas
Your Cache section stands outside the <form> tags as i see in the source code, so that could be why your fields are not submitted.
Put your form around the left/right div like this:
<div id="wrapper" align="center">
<div class="container" align="center">
<form id="formsite"> // your form starts here
<div id="left">
</div>
<div id="right">
</div>
</form>
</div>
</div>
Instead of this ( what you have right now ):
<div id="wrapper" align="center">
<div class="container" align="center">
<div id="left">
<form id="formsite"> // your form starts here
// the form will automatically be closed in this div
</div>
<div id="right">
</form> // this one will go away
</div>
</div>
</div>
Also, try to keep your code clean, For example:
var fieldWrapper = $('<div></div>',{
class: 'fieldwrapper',
id: 'field'+intId
});
This is way cleaner than:
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');

How Could i rearrange textboxes which are named as array index

i am working on a project in which i have to render rows dynamically . but user could also delete that row have a look at my current working
JQuery
var counter = 1;
function addrow() {
var textbox = "<div id='rows" + counter + "'> </br><label> Option : </label><input type='text' name='Answers[" + counter + "]' class='ahsan required' />Remove</div>";
var form = $("#form").valid();
if (form) {
$("#TextBoxesGroup").append(textbox);
counter++;
}
else {
return false;
}
}
html
<div id="TextBoxesGroup" style="margin-left: 100px;">
<div id="rows0">
</br><label>
Option :
</label>
<input type='text' name='Answers[0]' class='ahsan required' />Remove
</div>
</div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' /></div>
Now , if i have 10 rows there names will be Answers[0,1,2,3,4,5] . I want to remove input when i click on remove anchor and also reoder all textbox's name
For Example if i remove input at 4th index then all textbox automatically get re arranged . Can i Do it Please Help me and Thanks in Advance
You can make it without counter. This way your answers will be always ordered in the array starting by zero.
Here's a plausible solution:
$(function(){
$("#form").validate();
this.addrow = function() {
if ($("#form").valid()) {
var textbox = "<div> </br><label> Option : </label><input type='text' name='Answers["+$("#TextBoxesGroup div").length+"]' class='ahsan required' /><a class='remove-me' href='#'>Remove</a></div>";
$("#TextBoxesGroup").append(textbox);
$('.remove-me').click(function(){
$(this).parent().remove();
return false;
});
}
else {
return false;
}
}
this.addrow();
});
and the html is simple like this:
<form id="form">
<div id="TextBoxesGroup" style="margin-left: 100px;"></div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' />
</div>
</form>

Categories