Dynamic Form Input with Select - javascript

Trying my hand on dynamic form fields with itemz[].
I would like the form fields duplicate and have the select populate from the json object.
<!-- DYNAMIX ITEMS-->
<div class='container1'>
<tr>
<td>
<select id='itemz' name='itemz[]' class='itemz'> </select>
</td>
<td>
<input class='form-control' type='text' name='count[]' value=''>
<input class='form-control' type='hidden' name='weight[]' value='<?= $items['weight']; ?> '>
</td>
<!-- ADD MORE -->
<td>
<button class='add_form_field'>Add More</button>
</td>
</tr>
</div>
Here is the JS that is suppose to:
1) populate the drop down
but it only populates the first box, I tried using a for each on the class but no luck.
2) Duplicates the dropdown, but instead of appending after it adds it before the first main div
<script>
// POPULATING THE DROP DOWN
var obj={
Prod:
<?php echo $products; ?>
};
for(var i=0;i<obj.Prod.length;i++)
{
var option=$('<option></option>').text(obj.Prod[i]['item']);
$( ".itemz" ).append(option);
}
// DUPLICATING THE DROP DOWNS
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".container1"); //Fields wrapper
var add_button = $(".add_form_field"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append("<tr><td><select id='itemz' name='itemz[]' class='itemz'></select></td> <td><input class='form-control' type='text' name='count[]' value=''><input class='form-control' type='hidden' name='weight[]' value=''> </td> <td><a href='#' class='remove_field'>Remove</a> </td></tr></div>"); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Here is my JSON object:
Prod:
[{"id":"1","item":"Piano","weight":"200"},{"id":"2","item":"Fridge","weight":"50"},{"id":"3","item":"Freezer","weight":"100"},{"id":"4","item":"Sofa","weight":"20"},{"id":"5","item":"Microwave","weight":"10"},{"id":"6","item":"Dining Table","weight":"40"},{"id":"7","item":"Coffee Table","weight":"20"}]
};

var obj={
Prod:[
{
"id":"1",
"item":"Piano",
"weight":"200"
},{
"id":"2",
"item":"Fridge",
"weight":"50"
},{
"id":"3",
"item":"Freezer",
"weight":"100"
},{
"id":"4",
"item":"Sofa",
"weight":"20"
},{
"id":"5",
"item":"Microwave",
"weight":"10"
},{
"id":"6",
"item":"Dining Table",
"weight":"40"
},{
"id":"7",
"item":"Coffee Table",
"weight":"20"
}
]
};
var max_fields= 10;
var curent_fields=0;
function add_options(_el){
for(var key in obj.Prod){
var text=obj.Prod[key].item;
var id=obj.Prod[key].id;
var weight=obj.Prod[key].weight;
var el =$('<option/>').text(text).val(id).attr('weight',weight);
$(_el).append(el);
}
}
function add_controls(){
if(curent_fields>=max_fields){
alert('max feilds '+max_fields);
return false;
}
$('.container1').append('<tr><td><select name="itemz[]" class="itemz"></select></td><td><input class="form-control" type="text" name="count[]" value=""><input class="form-control" type="hidden" name="weight[]" value="">Remove</td><td>');
add_options($('.itemz').last());
$('.itemz').last().change(function(){
select_change(this);
});
$('.itemz').last().parent().next().find('.remove_field').click(function(){
$(this).parent().parent().remove();
curent_fields--;
});
curent_fields++;
}
function select_change(_el){
var curent_weight=$(_el).children(':selected').attr('weight');
var curent_id=$(_el).children(':selected').val();
var curent_item=$(_el).children(':selected').text();
//set hidden feid value
$(_el).parent().next().find('[name^="weight"]').val(curent_weight);
//your more code...
console.log([curent_id,curent_weight,curent_item]);
}
function start(){
add_options($('.itemz').last());
$('.itemz').last().change(function(){
select_change(this);
});
}
start();
$('.add_form_field').click(function(){
add_controls();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='container1'>
<tr>
<td>
<select id='itemz' name='itemz[]' class='itemz'> </select>
</td>
<td>
<input class='form-control' type='text' name='count[]' value=''>
<input class='form-control' type='hidden' name='weight[]' value=''>
</td>
<!-- ADD MORE -->
<td>
<button class='add_form_field'>Add More</button>
</td>
</tr>
</div>

Related

Change value of input pair javascript

For an application I am working on, I want to autocomplete a field using the input of the other field. My form will contain several pairs of inputs, which causes the problem for me to only change one specific input field.
$(function () {
$(".master").change(function () {
word = $(this).val();
$(this).parents('tr').find(".slave").val(word);
});
});
To add extra fields to the form, the script below is used.
$(document).ready(function() {
var max_fields = 1000; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<tr><td><div class="form-group"><input type="text" class="master" name="or['+x+']"></div></td><td> </td><td><div class="form-group"><input type="text" class="slave" name="tr['+x+']"></div></td></tr>'); //add input box
}
});
});
This is the form I'm using. This is one of the 100 rows in this form.
<form method="POST">
<table width="100%" class="input_fields_wrap">
<tr>
<td width="48%">
<div class="form-group">
<select id="original" name="original" class="form-control">
<option value="nederlands">Nederlands</option>
</select>
</div>
</td>
<td width="4%"></td>
<td width="48%">
<div class="form-group">
<select id="translated" name="translated" class="form-control">
<option value="frans">Frans</option>
</select>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group"><input type="text" class="master" name="or[0]"></div>
</td>
<td> </td>
<td>
<div class="form-group"><input type="text" class="slave" name="tr[0]"></div>
</td>
</tr>
</table>
<button type="submit" id="save" class="btn btn-success pull-right">Opslaan</button>
</form>
So just to be clear, I want to change the value of the "translation" input according to the value of the input in the same row. As my form contains so many rows, I don't know how to change that specific input according to the input in the same table row. Thanks in advance!
Here you go, I had to take out the ajax call but if you need help adding it back in just let me know.
I changed your html a bit by using classes instead of id's and this is the relevant js.
$(function () {
$("table").on('change', '.master', function () {
word = $(this).val();
$(this).parents('tr').find(".slave").val(word);
});
});
https://jsfiddle.net/6LaLm33t/4/
What you can do is get the parent, and then find the #translation of that parent. original and translation should probably be classes.
var word = '';
$(function () {
$(".original").change(function () {
word = $(this).val();
var arr;
$.ajax({ type: "POST", async: false, url: 'wordsuggestion' + word, success: function(data) {
arr = data;
$(this).parents('tr').find(".translation").val(arr);
}});
});
});
If you don't want (or can't, for some reason) to change HTML (you will have to do it, anyway, if there are multiple id's!), this is one of the ways to get desired result:
$('table tr td:first-child input').on("keyup", function() {
$(this).closest('tr').find('td:last-child input').val($(this).val());
});
So, if you have 3 cells (td's) in row, first selector will 'grab' first input, second one will find last/second input in the same row.
$('table tr td:first-child input').on("keyup", function() { //or desired event...change...input..
$(this).closest('tr').find('td:last-child input').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>
<div class="form-group"><div class="ui-widget"><input type="text" id="original" class="form-control" name="or[0]"></div></div>
</td>
<td> </td>
<td>
<div class="form-group"><input type="text" id="translation" class="form-control tags" name="tr[0]"></div>
</td>
</tr>
<tr><td>
<div class="form-group"><div class="ui-widget"><input type="text" id="original" class="form-control" name="or[0]"></div></div>
</td>
<td> </td>
<td>
<div class="form-group"><input type="text" id="translation1" class="form-control tags" name="tr[0]"></div>
</td>
</tr>
<tr><td>
<div class="form-group"><div class="ui-widget"><input type="text" id="original1" class="form-control" name="or[0]"></div></div>
</td>
<td> </td>
<td>
<div class="form-group"><input type="text" id="translation2" class="form-control tags" name="tr[0]"></div>
</td>
</tr>
</table>

add text field dynamically in to a html table

$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" name="Tape_Code[]" value=""/>delete</div>';
var x = 1;
$(addButton).click(function() {
if (x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<?php
include_once 'dpconnect.php';
$que=mysqli_query($MySQLiconn,"select Backup_Name from admin_backup_list ");
if(isset($_POST['confirm'])) {
$Date=date('d/m/y');
$Backup_Name=$_POST['Backup_Name'];
$Tape_Code = $_POST['Tape_Code'];
$Operator_Approval = $_POST['Operator_Approval'];
$Operator_Remark = $_POST['Operator_Remark'];
$abc=mysqli_query($MySQLiconn,"insert into backup_details(Date, Backup_Name, Tape_Code,Operator_Approval,Operator_Remark)values('$Backup_Name','$Tape_Code','$Operator_Approval','$Operator_Remark')");
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<?php $Date=date( 'd/m/y'); ?>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Date</td>
<td width="94">Backup_Name</td>
<td width="94">No Of Tapes</td>
<td width="53">Tape Code</td>
<td width="71">Operator Approval</td>
<td width="144">Operator Remark</td>
</tr>
<?php if ($que->num_rows > 0) { while ($row = mysqli_fetch_array($que)) { ?>
<tr>
<td>
<?php echo $Date; ?>
</td>
<td>
<?php echo $row[ 'Backup_Name']; ?>
</td>
<td>
<input type="text" name="No_Of_Backup">
</td>
<td>
<div class="field_wrapper">
<input type="text" name="Tape_Code" value="" />add
</div>
</td>
<td>
<input type="text" name="Operator_Approval">
</td>
<td>
<input type="text" name="Operator_Remark">
</td>
<td colspan="8">
<input type="submit" name="confirm" value="Confirm">
</center>
</td>
</tr>
<?php } } ?>
</table>
</form>
</body>
</html>
I'm doing this code in php. I need a help to add text fields dynamically in to the table's particular column. I have done the code using JavaScript also. But the problem is when I add field in one row, all rows are updating with extra fields. I need a help. How can I insert those data to MySQL?
The problem with your code is that you are using the class selector to select the elements. Class selector returns array like object of all the elements having that class.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
you can find out which element was clicked if you change your code similar to below one.
add
and in the script
function addButton(ev) {
var clickedElement = console.log(ev.target);
}
Now you have the element which was clicked by user and you can find the parent td/tr and append html for textbox.
In $Tape_Code = $_POST['Tape_Code']; You will get array of text input you have to insert it in database in form that you want.
$Tape_Code = $_POST['Tape_Code']
foreach($Tape_Code as $code){
echo $code;
}

Show all names found in table when click display button

I need to show all names found in table #tb and display as list using jQuery when the user clicks the display button.
My code is below. I can add successfully, but how can I take data from column name and show as list?
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function () {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function () {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
});
</script>
<style>
.editing {
background: yellow;
}
</style>
</head>
<body>
<div>
ID
<input type="text" id="txt1" /><br />
Name
<input type="text" id="txt2" /><br />
Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select><br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
</div>
</body>
</html>
Try this:
https://jsfiddle.net/ionutmihai1995/euk6xkzp/
$('#btndis').click(function(){
$('ul').empty();
$("#tb").find('tr').each(function(i,el){
var $tds = $(this).find('td');
//for name
$('ul').append("<li>"+$tds.eq(1).text()+"</li>");
});
});
Please check below code.
$("#btndis").on('click',function(){
$("body").append("<ul id='listNames''></ul>");
$('#tb td:nth-child(2)').each(function() {
$("#listNames").append("<li>"+$(this).text()+"</li>")
});
})
Please refer code on this Link. https://jsfiddle.net/gq5f5ux2/2/
On click of the display button iterate loop through all the tr>td-second child to get all the names and then append a UL and LI in the body to display list all the names.
Add a class for colum called "name" and then you can iterate over and select the text in the element
<td class="name">John</td>
Then in JQuery:
$(document).ready(function() {
$('#tb').find('tr').each(function() {
var name = $(this).find('.name').text();
$('#result').append('<p>'+name+'</p>');
});
});
Working example
check this JsFiddle Demo
HTML
<div>
ID
<input type="text" id="txt1" />
<br /> Name
<input type="text" id="txt2" />
<br /> Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select>
<br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
<ul id="ulNames">
</ul>
</div>
JS
$(function() {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function() {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function() {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
$('#btndis').on('click', function() {
//gets table
var oTable = document.getElementById('tb');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
// get your cell info here
var cellVal = oCells.item(1).innerHTML;
$('#ulNames').append('<li>' + cellVal + '</li>');
}
});
});
CSS
.editing {
background: yellow;
}
$("#btndis").click(function() {
$("body").append("ul");
for(var i = 1; i <= $("tr > td").length; i++) {
$("ul").append("li").addClass("li.li-"+i);
$("li.li-"+i).append($("td:nth-child("+i+")").text());
}
}
Explanation :
First, we create the ul to store data. Then, we iterate each tr child (td) with a for loop, we create a li and store data into it. It will be displayed in a list, as asked.

Deleting input fields dynamically that dont have a unique attribute

I have a dynamic form that allows fields to be added and deleted dynamically with the help of jquery. The existing fields are autopopulated from values in mysql table. The add button adds a new input field while the delete button removes an input field. The fields loaded with values from the db are tagged with data-saved attributed. Now my dilemma is focused in the delete button. How can I delete new sections that are not tagged with data-saved attribute? EXAMPLE
JQUERY
$(document).ready(function () {
$('#btnAdd').click(function () {
var $clones = $('#input_table tr'),
num = $clones.size() + 1,
next_num = parseInt($clones.last().find('input[name^="person_id"]').val()) + 1,
$template = $clones.first(),
newSection = $template.clone().attr('id', 'pq_entry_'+num),
person_id = 'person_id_'+num;
person_fname = 'person_fname_'+num;
person_status = 'person_status_'+num;
newSection.removeAttr('data-saved');
// clear out all sections of new input
newSection.find('input').val('');
newSection.find('select').val([]);
newSection.find('input[name^="person_id"]').attr({
'id': person_id,
'name': person_id
}).val();
newSection.find('input[name^="person_fname"]').attr({
'id': person_fname,
'name': person_fname,
'placeholder' : 'Person #'+num+' First Name'
}).val();
newSection.find('select').attr({
'id': person_status,
'name': person_status
}).val(next_num);
newSection.find('input[type="button"]').attr('data-ident', next_num);
$('#input_table').append(newSection);
$('#btnDel').prop('disabled', '');
if (num == 100) $('#btnAdd').prop('disabled', 'disabled');
});
$('#btnDel').click(function () {
var num = $('.clonedSection').length; // how many duplicate input fields we currently have
$('#pq_entry_' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').prop('disabled', '');
// if only one element remains, disable the "remove" button
if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');
});
$('#btnDel').prop('disabled', 'disabled');
});
HTML
<tbody id="input_table" >
<tr id="pq_entry_1" class="clonedSection" data-saved="1">
<td><input type="text" name="person_id" value='1' readonly /></td>
<td>
<input id="person_id_1" name="person_id_1" type="text" value='1'/>
<input id="person_fname_1" name="person_fname" placeholder=" First Name" type="text" value='James'/>
</td>
<td>
<select id="person_status_1" name="person_status_1"></select>
</td>
</tr>
<tr id="pq_entry_2" class="clonedSection" data-saved="2">
<td><input type="text" name="person_id" value='2' readonly /></td>
<td>
<input id="person_id_2" name="person_id_2" type="text" value='2'/><input id="person_fname_2" name="person_fname" placeholder=" First Name" type="text" value='Cynthia'/>
</td>
<td>
<select id="person_status_2" name="person_status_2"></select>
</td>
</tr>
</tbody>
<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='Delete New Field' /></br>
From
$('#pq_entry_' + num).remove(); // remove the last element
Change into
var toDelete = $('#pq_entry_' + num).not('[data-saved]');
if (toDelete.length) {
// Last one wasn't a db-entry
toDelete.remove();
// enable the "add" button
$('#btnAdd').prop('disabled', '');
// if only one element remains, disable the "remove" button
if ($('.clonedSection:not([data-saved])').length == 0)
$('#btnDel').prop('disabled', 'disabled');
}
Working example: http://jsfiddle.net/az9LQ/
You can simplify it a lot:
Add a <script type="text/template"> element which can hold the HTML to be appended each time (it won't be visible on the page). I've substituted $1 for the row number which you are dynamically updating and all occurrences of $1 can be replaced in a single shot (and if you want to replace other values then you can extend this and use $2, $3, ... $n for multiple substitutions).
Set up various static variables outside the 'click' handlers including an addedRows array to store the rows as they are added.
In the 'add' handler:
Create the row from the template, replacing $1 with the row number;
Store the row in an addedRows array for later use in the 'delete' handler;
Dynamically update elements as needed; and
Update the buttons.
In the 'delete' handler:
The addedRows array stores all references to the dynamically added rows so just pop() the last row from the array and remove() it;
Update the buttons.
JSFIDDLE
HTML:
<table>
<tbody id="input_table" >
<tr id="pq_entry_1" class="clonedSection" data-saved="1">
<td><input type="text" name="person_id" value='1' readonly /></td>
<td>
<input id="person_id_1" name="person_id_1" type="text" value='1'/>
<input id="person_fname_1" name="person_fname" placeholder=" First Name" type="text" value='James'/>
</td>
<td>
<select id="person_status_1" name="person_status_1"></select>
</td>
</tr>
<tr id="pq_entry_2" class="clonedSection" data-saved="2">
<td><input type="text" name="person_id" value='2' readonly /></td>
<td>
<input id="person_id_2" name="person_id_2" type="text" value='2'/><input id="person_fname_2" name="person_fname" placeholder=" First Name" type="text" value='Cynthia'/>
</td>
<td>
<select id="person_status_2" name="person_status_2"></select>
</td>
</tr>
</tbody>
</table>
<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='Delete New Field' /></br>
<script type="text/template" id="template">
<tr id="pq_entry_$1" class="clonedSection">
<td><input type="text" name="person_id" value="$1" readonly /></td>
<td>
<input id="person_id_$1" name="person_id_$1" type="text"/>
<input id="person_fname_$1" name="person_fname" placeholder="Person #$1 First Name" type="text" />
</td>
<td>
<select id="person_status_$1" name="person_status_$1"></select>
</td>
</tr>
</script>
JavaScript:
$(document).ready(function () {
var template = $('#template' ).html(),
$input_table = $( '#input_table' ),
addedRows = [],
num_saved_rows = $('#input_table tr').length;
$('#btnAdd').click(function () {
var row = $( template.replace( /\$1/g, num_saved_rows + addedRows.length + 1 ) )
.appendTo( $input_table );
addedRows.push( row );
$('#btnDel').prop('disabled', num_saved_rows + addedRows.length == 100 );
// Not sure what you are doing with the 'select' element but you can
// dynamically update the attributes of any element like this:
$( 'select', row ).val( '' );
});
$('#btnDel').click(function () {
if ( addedRows.length )
{
addedRows.pop().remove();
$('#btnAdd').prop('disabled', false);
$('#btnDel').prop('disabled', !addedRows.length);
}
});
$('#btnDel').prop('disabled', 'disabled');
});
Not sure what you are trying to do with the select element as it has no OPTION children.

Adding new row to the table using javascript / jquery

I want to add row to the table on clicking Add button and delete row using Delete button using javascript/jquery. I have tried writing the following code:
<script src="/js/jquery-2.0.3.js"></script>
<script>
/* Javascript for phone numbers*/
$(document).ready(function()
{
var counter = 2;
var count= 4;
$("#add_phone").click(function()
{
alert("whoah it worked");
if(counter>=count)
{
alert("Only " + count + " Phone number allowed.");
return false;
}
var htmlToAppend = '<tr id="pn'+ counter +'"><th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
newTableRow.appendTo("#phone_number");
counter++;
});
$("#delete_phone").click(function()
{
if(counter==2)
{
alert("Cannot remove phone number");
return false;
}
counter--;
$("#pn" + counter-1).remove();
});
});
But the alert message alert("whoah it worked"); doesn't get displayed i.e its not entering the function.
<div class="info_type">
Phone numbers <hr>
<table id="phone_number">
<tr id="pn1">
<th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td>
</tr>
</table>
<input type="button" id="add_phone" value="Add"/>
<input type="button" id="delete_phone" value="Delete"/>
</div>
I really want this solution. Can anybody help me??
PS: I am using Ruby on rails
Your string append is not well formed.
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"> <option value="home">home</option> <option value="Business">Business</option> <option value="Business2">Business 2</option></select> </th><td><input type="text"/></td></tr>';
Working sample in fiddle http://jsfiddle.net/shree/jNA4x/
try to rewrite htmlToAppend variable with a \n\ in the end of each line
demo
You can't have line breaks in your htmlToAppend variable,
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"><option value="home">home</option><option value="Business">Business</option><option value="Business2">Business 2</option></select></th><td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
Example Code
A common pitfall for me as well.
increment the counter you did not increments it.
for more help use like the below example.
<html>
<h1>Add remove dynamically</h1>
<head>
<title></title>
</head>
<body>
Living in:
<table id="purchaseItems" name="purchaseItems" style="display: inline-table;">
<tr id="tr_1">
<td>
<input type="text" name="living_1" class="tbDescription next" required />
</td>
<td>
<input type="text" name="biggest_1" class="next" required />
</td>
<td>
<input type="text" name="nextbiggest_1" class="nextRow" required />
</td>
<td>
<input type="button" name="addRow[]" id="remove_1" class="removeRow" value='-' />
</td>
<td>
<input type="button" name="addRow[]" id="add_1" class="add" value='+' />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$("#remove_1").hide();
$(document).ready(function () {
$(document).on('click', '#purchaseItems .add', function () {
var total_row = $('#purchaseItems tr').length;
var rows = $('#purchaseItems tr').length+1;
if(total_row < 5)
{
// clear the values
$('#purchaseItems tr:last').after('<tr id="tr_'+rows+'"><td><input type="text" name="living_'+rows+'" id="living_'+rows+'" class="tbDescription next"></td><td><input type="text" name="biggest_'+rows+'" id="biggest_'+rows+'" class="next"></td><td><input type="text" name="nextbiggest_'+rows+'" id="nextbiggest_'+rows+'" class="nextRow"></td><td><input type="button" name="addRow[]" id="remove_'+rows+'" class="removeRow" value="-"></td><td><input type="button" name="addRow[]" id="add_'+rows+'" class="add" value="+"></td></tr>');
$(".add").hide();
$(".removeRow").show();
$("#add_"+rows).show();
}
else
{
alert("Maximum limit reached.")
}
});
$(document).on('keypress', '#purchaseItems .next', function (e) {
if (e.which == 13) {
var v = $(this).index('input:text');
var n = v + 1;
$('input:text').eq(n).focus();
//$(this).next().focus();
}
});
$(document).on('keypress', '#purchaseItems .nextRow', function (e) {
if (e.which == 13) {
$(this).closest('tr').find('.add').trigger('click');
$(this).closest('tr').next().find('input:first').focus();
}
});
$(document).on('click', '#purchaseItems .removeRow', function () {
var total_row = $('#purchaseItems tr').length;
if ($('#purchaseItems .add').length > 1) {
$(this).closest('tr').remove();
var last_tr_id = $('#purchaseItems tr:last').attr("id").split("_")[1];
$("#add_"+last_tr_id).show();
}
if ($('#purchaseItems .add').length == 1) {
$(".removeRow").hide();
}
});
});
</script>
Try this way using Jquery
<form id="myForm">
<div class="clonedInput">
<input type="text" class="phone_oa" id="textPhone1" name="input1" placeholder="Enter phone number" style="width: 110px;" />
<input type="button" name="btnDelete1" class="btnDel" value="Remove" disabled="disabled" />
</div>
<div id="addDelButtons" style="margin-top: 10px;">
<button type="button" id="btnAdd" class="btn" >Add Another Number</button>
</div>
</form>
Script
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name','input'+ (++inputs) ).val('');
c.children(':text').attr('id','textPhone'+ (inputs) ).val('');
c.children(':button').attr('name','btnDelete'+ (inputs) );
$('.clonedInput:last').after(c);
$('#btnAdd').attr('disabled',($('.clonedInput').length > 4));
});
$('.btnDel').click(function() {
if (confirm('Confirm delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled',($('.clonedInput').length < 2));
$('#btnAdd:disabled').removeAttr('disabled');
fixNames();
}
});
function fixNames(){
var i = inputs;
while(i--) {
$('input:text')[i].name = 'input'+ (i+1);
$('input:button')[i].name = 'btnDelete'+ (i+1);
}
}
DEMO

Categories

Resources