How to dynamically Add and Remove multiple <tr> with input fields - javascript

What i m trying to do is when the user type number quantity automatically jquery must create that number of with inputs.
so i used this code to generate
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});
If the user type 5 then it creates 4 now if the user change the value and type 7 then have to remove the previous created those 4 and then have to create 6
now i dont know how to remove

Empty before looping, and start at zero
$( "#cont_qty" ).change(function() {
var cont_qty = this.value;
$("#munna").empty();
for(var i=0 ; cont_qty>i; i++) {
itemCount++;
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});

use Html() not append()
$("#cont_qty").change(function () {
var cont_qty = this.value;
var html = "";
for (var i = 1; cont_qty >= i; i++) {
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr' + itemCount + '"><td><input class="input-medium" type="text" id="cont_no' + itemCount + '" name="cont_no' + itemCount + '" value=""></td></tr>';
}
$("#munna").html(html);
});

$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
var html = '';
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html);
});

To prevent it from creating one less than you want, change this:
for(var i=1 ; cont_qty>i; i++)
to this:
for(var i=1 ; i<=cont_qty; i++)
And, has already been stated, as you want to reset the amount of fields everytime you change the number, change $("#munna").append(html); to $("#munna").html(html);

$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html)
});
Beside of use 'append' the html div, .html can reload the div content.

change the whole html content of #munna with html()
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(auto_tr)
});

You have to use .html() instead of .append() outside of your loop.
$("#munna").html(html);
Instead of
$("#munna").append(html);

Related

How to delete the selected file from array using JavaScript

I am trying to call the delete button to remove the listed file. Can anyone help me to build the logic.
$(document).ready(function () {
$('input[type = "file"]').change(function (e) {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
HTML += "<tr><td>" + input.files.item(i).name + "</td><td> <button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML = HTML;
});
});
You can remove the parent tr tag containing button delete like
$('.btnDelete').on('click', function () {
$(this).closest('tr').remove();
});

jQuery: building a form dynamically from an array with a for loop

I have a jQuery function that receives id of div element and json array
function FormBuilder(selector,myList){
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
if(rowHash['id'] > 0 ){
$(selector).append('<form id="DialerInfo">');
for (var key in rowHash) {
$(selector).append(key +': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
$(selector).append('</form>');
}
}
}
And I expected this to build a proper form, i.e. all inputs should be between <form> and </form> tags. But I'm receiving something completely different:
First goes
<form id="DialerInfo"></form>
then below all input fields. Why are they outside the form tags? does jQuery close all tags automatically? how to prevent this behavior then?
DOM creation using jQuery doesn't work like string concatenation
You can create a form and append all the elements to it
function FormBuilder(selector, myList) {
var $form = $('<form id="DialerInfo"></form>').appendTo(selector);
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
if (rowHash['id'] > 0) {
for (var key in rowHash) {
$form.append(key + ': <input type="text" name="' + key + '" value="' + rowHash[key] + '"><br/>');
}
}
}
}
//use
$.each(arrayorJSON,function(KEY,VALUE){
//YOUR CODE HERE
})
//it is a jquery looper which accepts both array and json values and compatible with all browsers instead of for loop

After deletion changing id of textbox inside cell id not working

I have table using Javascript and I am deleting the rows using a delete function
After the deletion I am trying to reindex the table cell ids
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++){
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
}
}
But the following lines not working:
table.rows[i].cells[1].id="notes_"+i;
table.rows[i].cells[2].id="amount"+i;
<td>'s contains input boxes, it will be like this
<td><input type="text" title="notes"></td>
<td><input type="text" title="amount"></td>
How can I change the id of text box inside <td> or cell ?
I made a jsfiddle here https://jsfiddle.net/an87ka5p/
I updated this to answer the question in the comments
function test() {
var table = document.getElementById("ordertable");
var rowcountAfterDelete = table.rows.length;
for (var i = 0; i < rowcountAfterDelete; i++) {
table.rows[i].id = "row_" + i;
table.rows[i].cells[0].innerHTML = i + "<input type='checkbox' id='chk_" + i + "'>";
table.rows[i].cells[1].getElementsByTagName("input")[0].id = "notes_" + i;
table.rows[i].cells[2].getElementsByTagName("input")[0].id = "amount_" + i;
}
}

For loop inside a each function, add option selected

Code: Fetch JSON and create cart contents. Create a list of each products info, and have a form required for each product to update qty
$.ajax({
url: "myurl",
type: 'POST',
dataType: "json"
}).done(function(response){
$.each(response,function(k,v){
//UL this products info list was here
var otions = '';
for( i=1; i<20; i++ ){
options += '<option value="'+i+'">'+i+'</option>';
}
var form = '<form action="myurl" method="post" accept-charset="utf-8"><label for="products_qty">Quantity</label>'
+'<select name="products_qty>'
+options
+'</select>'
+'<input type="hidden" name="row_id" value="17e62166fc8586dfa4d1bc0e1742c08b" />'
+'<input type="submit" name="submit_item" value="Update" /></form>';
$('#formWrapper').append(form);
});
});
The code runs well. In the for loop I need to add selected=selected to a particular option tag.How and where will this be added.
Can a if statement be achieved inside for loop?
var otions = '';
for( i=1; i<20; i++ )
{
if(i=7)
{
var select = 'selected="selected"';
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}
Ive seen the following link and tried adding their stuff just before my apped, and no luck.
set option "selected" attribute from dynamic created option
Try this changes,
var otions = '';
for( i=1; i<20; i++ ){
if(i==7){
options += '<option value="'+i+'" selected="selected">'+i+'</option>';
}
else
options += '<option value="'+i+'" +select+>'+i+'</option>';
}
The problem with your code:
var otions = '';
for( i=1; i<20; i++ )
{
if(i=7)
{
var select = 'selected="selected"';
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}
... is that select only exists inside the if statement, because that's where you're defining it.
So:
var otions = '';
for( i=1; i<20; i++ )
{
var select;
if(i=7)
{
select = 'selected="selected"';
}
else
{
select = "";
}
options += '<option value="'+i+'" '+select+'>'+i+'</option>';
}
Maybe this is what you want:
var select = i === 7 ? " selected='selected'" : '';
options += "<option value='"+i+"'"+select+'>'+i+'</option>';

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

Categories

Resources