jquery create dynamic div inside div - javascript

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.

Related

How to turn a form into 2 arrays [duplicate]

This question already has answers here:
How to get a form input array into a PHP array
(9 answers)
Closed 6 years ago.
I have a simple form with two text boxes: One for peoples "name" and the other for their "surname". On the page you can click and it will add two more text boxes below, also for "name" and "surname".. so basically you could add as many pairs of name and surname as you want.
How do I take all that information and turn it into two arrays, one for "names" and one for "surnames"?
You can see the demo here: http://poostudios.com/jstest2.html
Here's the code:
<html>
<head>
<script type="text/javascript" src="nutrition/jquery-3.1.1.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>enter code here
</head>
<body>
<form action="results.php" method="get">
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Name : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" ><label> Surname : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Name : </label><input type='textbox' id='textbox1' >
<label>Surname : </label> <input type='textbox' id='textbox2' >
</div>
</div>
<input type='button' value='Add' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
<input type="submit" value="Go">
</form>
</body>
</html>
I was created with two array all name =>names[],all surename =>surenames[] .and click the go button .You will see the console.log .It will shown
And also created the class name with textbox. Beacause class name only adapted with each function.
var names=[];
var surenames=[];
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Name : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox1" class="textbox1" value="" ><label> Surname : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox2" class="textbox2" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
counter--;
$("#TextBoxDiv" + counter).remove();
});
$('input[type=submit]').click(function (e){
e.preventDefault();
var names = $('.textbox1').map(function (){
return this.value
}).get();
var surenames = $('.textbox2').map(function (){
return this.value
}).get();
console.log('names='+names);
console.log('surenames='+surenames);
})
});
div{
padding:8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="results.php" method="get">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Name : </label><input type='textbox' class="textbox1" id='textbox1' >
<label>Surname : </label> <input type='textbox' class="textbox2"id='textbox2' >
</div>
</div>
<input type='button' value='Add' id='addButton'>
<input type='button' value='Remove' id='removeButton'>
<input type="submit" value="Go">
</form>

add event to dynamically created button [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
Here i am creating dynamic radio buttons, text area and click events but my click events for add and remove button is not working for the dynamically created button. I tried using on click event of jquery but it is not working as expecte. How to add .on jquery function in my scenario i tried using :
$("#TextBoxesGroup")‌​.on("click", ".abc", (function () {
//some script
});
but when i click on the new dynamic add button which i created it is not at all adding another block
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var counter = 2;
alert(123);
$(".abc").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="" ><br><input type="radio" name="gender' + counter + ' value="male" > Male<input type="radio" name="gender' + counter + ' value="male" > Female<br><textarea id="textbox' + counter + ' rows="4" cols="50"></textarea><input type="button" class="abc" id="addButton' + counter + '" value="Add Button" ><input type="button" id="removeButton' + counter + '" value="Remove Button" >');
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>
</head>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br>
<textarea id="textbox" rows="4" cols="50"></textarea>
<input type='button' class="abc" value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</div>
Use event delegation.
$(".abc").on('click',function(){
//add your script
})
OR
$("immediate_parent_id_or_class").on('click',".abc",function(){
//add your script
})

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>

How to add a new textfield on clicking a button?

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.

Cannot use show/hide

My issue: When I add another text input, I cannot show/hide it.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.min.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
$(".slidingDiv1").hide();
$(".show_hide1").show();
$('.show_hide1').click(function(){
$(".slidingDiv1").slideToggle();
});
});
var counter = 1;
var limit = 3;
function addInput(divName){
mainCanvasDiv = document.createElement("div");
mainCanvasDiv.className = "slidingDiv1";
mainCanvasDiv.style.display = "none";
var newdiv = document.createElement('div');
newdiv.id = "dynamicInput" + counter;
newdiv.innerHTML = "<a href='#' class='show_hide1'>Show/hide</a>";
mainCanvasDiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='dynamicInput" + counter +"1'><br><input type='text' name='dynamicInput" + counter +"2'>";
document.getElementById(divName).appendChild(newdiv).appendChild(mainCanvasDiv);
counter++;
}
$(document).ready(function(){
$('#sortable').sortable({
update: function(event, ui) {
var newOrder = $(this).sortable('toArray').toString();
document.getElementById('sort').value = newOrder;
}
});
});
</script>
</head>
<body>
<form action="lost.php" method="POST">
<div id="sortable">
<div id="dynamicInput">
Show/hide
<div class="slidingDiv">
<input type="text" name="myInputs[]">
</div>
</div>
</div>
<input type="button" value="Add another text input" onClick="addInput('sortable');"><br />
<input type="hidden" name="sort" id="sort" value="">
<input type=submit value="GO!">
</form>
</body>
</html>
Any advice?
Update:
I have changed
$('.show_hide1').click(function(){
to
$('.show_hide1').on("click", "div a.show_hide1", function(){
Maybe I am doing something wrong, I am not strong in JS.
Fixed: http://jsfiddle.net/Yhp3c/
You need to use live instead of click as live also targets future (read: DOM scripted) elements.
Edit: As stated in comments: Use on instead of live.
Replace your click events for:
$("#sortable").on("click","div a.show_hide", function() {
$(".slidingDiv").slideToggle();
});
$("#sortable").on("click","div a.show_hide1", function() {
$(".slidingDiv1").slideToggle();
});

Categories