Create array based on user entered inputs - javascript

I have table/form where the length is dynamic (user can add/delete rows). I would like to create an array onsubmit containing the values the user has entered and use console.log to show the array values as well as the length of array.
HTML
<div class="container">
<form id="online1" action="#">
<table class="table" id="tblData">
<thead>
<tr>
<th>Youtube ID</th>
<th>Add/Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control song-input" placeholder="5YCcad6hklE" />
</td>
<td>
<button type="button" class="btn btn-default btn-add">Add</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="t6Lr8ggJWi4" />
</td>
<td>
<button type="button" class="btn btn-danger btn-del">Del</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="YmzfaapaPMA" />
</td>
<td>
<button type="button" class="btn btn-danger btn-del">Del</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
jQuery
jQuery(".btn-primary").click(function(){
var values = [];
$('.yt-mix').each(function() {
values[this.name] = this.value;
});
var mix_size = values.length;
console.log(values); // "5YCcad6hklE", "t6Lr8ggJWi4", "YmzfaapaPMA"
console.log(mix_size); // 3 rows
});
Working on this fiddle http://jsfiddle.net/1jmjdxLL/

You can use each to loop over all the textboxes. :text pseudo-selector selects all the textboxes.
$(document).ready(function() {
$(document).on('click', '.btn-primary', function() {
var values = [];
$('#tblData :text').each(function() {
if ($(this).val()) {
values.push($(this).val());
}
});
console.log(values);
console.log(values.length);
});
});
Demo: https://jsfiddle.net/tusharj/1jmjdxLL/1/

$(".btn-primary").click(function(){
var values = [];
$('#tblData input').each(function() {
values.push($(this).val());
});
var mix_size = values.length;
console.log(values); // "5YCcad6hklE", "t6Lr8ggJWi4", "YmzfaapaPMA"
console.log(mix_size); // 3 rows
});

Related

How to output in console or json a data structured with correct column and row values?

I have this table:
<button type="button" class="btn btn-danger" id="saveTable">Save table</button>
<table id="table-data" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th></th>
<th>
<button type="button" class="btn btn-primary removeColumn btn-block">Delete column</button>
<br>
<input class="form-control column_data" type="text" autofocus="" placeholder="Title" name="Name" value="Titolo">
</th>
<th>
<button type="button" class="btn btn-primary removeColumn btn-block">Delete column</button>
<br>
<input class="form-control column_data" type="text" autofocus="" placeholder="Title" name="Name">
</th>
</tr>
</thead>
<tbody>
<tr class="tr_clone">
<td><button type="button" class="btn btn-primary removeRow">Delete row</button></td>
<td><input class="form-control row_data" type="text" autofocus="" placeholder="data" name="who" value="22"></td>
<td><input type="text" placeholder="data" name="datepicker_end" class="form-control row_data"></td>
</tr>
</tbody>
</table>
When I click the save button, I would like to output either in console.log or ideally as a jSon. The issue I am facing is that columns and rows do not follow the correct index:
$('#saveTable').on("click", function() {
$(".column_data").each(function(){
var dataValue = $(this).val();
console.log(dataValue + "\n");
$(".row_data").each(function(){
var dataValue = $(this).val();
console.log(dataValue + "\n");
});
});
});
JsFiddle playground
I just had some free time to take a look and try to implement what I mentioned in the comments.
It was a bit tricky to implement, as you don't directly access the table's rows and columns, and especially the way you wanted to group rows and columns, but with some algorithm magic, and the power of maths I managed to get it working.
Here is a working example where I print both row,column data, and I also build a custom object as you were trying where the column_data are the keys and row_data are the values in a list depending how many rows per column there are.
$('#saveTable').on("click", function() {
var colCounter = $(".column_data").length;
var rowCounter = $(".row_data").length;
var customObject = {};
for (var i = 0; i < colCounter; i++) {
console.log("Col-data: " + $(".column_data").eq(i).val());
customObject[$(".column_data").eq(i).val()] = [];
for (var j = 0 + i; j < rowCounter; j += colCounter) {
console.log("Row-data: " + $(".row_data").eq(j).val());
customObject[$(".column_data").eq(i).val()].push($(".row_data").eq(j).val());
}
}
console.log(customObject);
});
$('#table-data input').on("change", function() {
$(this).attr("value", $(this).attr("value"));
});
$(".table-striped tbody tr th input").each(function() {
$(this).addClass("column_data");
});
$("#addTr").on('click', function() {
var $tr = $('tbody tr.tr_clone');
var $clone = $tr.clone();
$clone.find(':text').val('');
$tr.after($clone);
$(".table-striped tbody tr td input").each(function() {
$(this).addClass("row_data");
});
});
$("#addTd").on("click", function() {
$(".table-striped thead tr").append('<th><button type="button" class="btn btn-primary removeColumn btn-block">Delete column</button><br><input class="form-control" type="text" autofocus placeholder="Title" name="Name"></th>');
$(".table-striped tbody tr").append('</td> <td><input type="text" placeholder="data" name="datepicker_end" class="form-control"></td>');
$(document).find("thead th input").each(function() {
$(this).addClass("column_data");
});
$(".table-striped tbody tr td input").each(function() {
$(this).addClass("row_data");
});
});
$(document).on("click", ".removeRow", function() {
$(this).parent().parent()
$(this).parent().parent().remove();
});
$(document).on("click", ".removeColumn", function() {
var index = $(this).parent().index() + 1;
$(this).closest("table").find("td:nth-child(" + index + ")").remove();
$(this).parent().remove();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col">
<hr>
<h3>Insert your data</h3>
<button id="addTd" type="button" class="btn btn-primary">
Add Column
</button>
<button id="addTr" type="button" class="btn btn-primary">
Add Row
</button>
<button type="button" class="btn btn-danger" id="saveTable">Save table</button>
<hr>
<div class="table-responsive">
<table id="table-data" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th></th>
<th>
<button type="button" class="btn btn-primary removeColumn btn-block">Delete column</button>
<br>
<input class="form-control column_data" type="text" autofocus placeholder="Title" name="Name" value="">
</th>
</tr>
</thead>
<tbody>
<tr class="tr_clone">
<td><button type="button" class="btn btn-primary removeRow">Delete row</button></td>
<td><input class="form-control row_data" type="text" autofocus placeholder="data" name="who" value=""></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
I hope this helps!

Input element added does not appear on PHP post

I have tried to add input text element to my form
through this jquery code below
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="" name="item'+counter+'"/></td>';
cols += '<td><input type="text" class="" name="rate'+counter+'"/></td>';
cols += '<td><input type="text" class="" name="quantity'+counter+'"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("#myTable").append(newRow);
$("#itemcounter").val(counter);
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
var count = $("#itemcounter").val();
$("#itemcounter").val(count-1);
counter = count -1;
});
});
Now the form is as below:
<form action="{{url('/billgenerate')}}" method="post">
<input type="hidden" name="itemcounter" id="itemcounter" value="">
<table id="myTable" class="table order-list">
<thead>
<tr>
<td>Item Name</td>
<td>Rate</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-4">
<input type="text" name="item0" class="" style="width:22em" />
</td>
<td class="col-sm-3">
<input type="text" name="rate0" class=""/>
</td>
<td class="col-sm-3">
<input type="text" name="quantity0" class=""/>
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block" name="addrow" id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</form>
when I add add new row, it adds successfully, and also the element is added with its name increment by 1 so that while posting the page the name does not get conflicts.
but when I try to add a input predefined inside the table, php recognizes that particular element.
but when I try to add it through jquery code, it does not return the elements which are added. where am i going wrong?

How to fetch the last row data using .val() from a table and show it in alert using jquery?

This is my script code.
$(document).ready(function() {
$(".add-row").click(function() {
var name = $("#name").val();
var markup = "<tr><td>" + name + "</td></tr>";
$("table tbody").append(markup);
});
$(".bttn").click(function() {
var i = $("#tab").find("tr").last().val();
alert(i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="name" placeholder="Name">
<input type="button" class="add-row" value="Add Row">
</form>
<table id="tab">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Peter Parker</td>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
<button type="button" class="bttn">show Row</button>
I have a table in which it adds rows when "add row" button is clicked. Every time if I press "show row" button, the last row data should be shown in alert prompt. How to do that using Jquery?
You need to use .text() as TR element doesn't have value property.
$("#tab").find("tr").last().text()
$(document).ready(function() {
$(".add-row").click(function() {
var name = $("#name").val();
var markup = "<tr><td>" + name + "</td></tr>";
$("table tbody").append(markup);
});
$(".bttn").click(function() {
var i = $("#tab").find("tr").last().text().trim();
alert(i);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="name" placeholder="Name">
<input type="button" class="add-row" value="Add Row">
</form>
<table id="tab">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Peter Parker</td>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
<button type="button" class="bttn">show Row</button>
with .val() you can't achieve this because .val() works with input field, and for getting innerHTML you have to use .text()
You can print any of row/column content using this
var value= $("#tab tr:eq(2) td:eq(4)").text();
alert(value)
and for last row use:
alert($('#tab tr:last').text());

jQuery Remove by id

I am adding test in a fieldset and while I can add them, I am unsure how to write the correct function to remove them. I had it working in javascript but was asked to write it using JQuery and cannot seem to make it work. All example I have researched don't seem to work with my original cloning function which builds a remove button in it. The fieldsets also duplicate and I have the code working for that already, just need a little help with this remove event function.
Here it the javascript/jquery:
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('dataTes');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "dataTes" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
function remove(){
}
Here is the html :
<fieldset>
<legend>Test</legend>
<input type="submit" class="button" id = "button" value="+" onlick="duplicate()" title = "#">
<input type="submit" class="button" id = "button" value="-" onlick="remove()" title = "#">
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td width="2px"><input type="text" name="usrname"></td>
<td>
<input type="submit" class="button" id = "add" value="+" onClick="addRow('#')" title = "#">
<input type="submit" class="button" id = "add" value="-" onClick="deleteRow('#')" title = "#">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td><input type="text" name="usrname"></td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td><input type="text" name="usrname"></td>
</tr>
<table id="dataID" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Here is the quick and complete solution. Remove your inline functions to elements add and remove buttons and attach event to their id as below:
var id = 0; //global id to create unique id
$(document).ready(function() {
//attach click event to element/button with id add and remove
$("#add,#remove").on('click', function() {
var currentElemID = $(this).attr('id'); //get the element clicked
if (currentElemID == "add") { //if it is add elem
var cloneParent = $("#dataTes").clone(); //clone the dataTes element
id=$("div[id^=dataTes]").length;//get the count of dataTes element
//it will be always more than last count each time
cloneParent.find('[id]').each(function() {
//loop through each element which has id attribute in cloned set and replace them
//with incremented value
var $el = $(this); //get the element
$el.attr('id', $el.attr('id') + id);
//ids would now be add1,add2 etc.,
});
cloneParent.attr('id', cloneParent.attr('id') + id);//replace cloneParent id
cloneParent.appendTo('fieldset');//append the element to fieldset
$("#remove").show();//show remove button only if there is more than one dataTes element
} else {
$("div[id^=dataTes]:last").remove();
//just remove the last dataTes
//[id^=dataTes]:last annotates remove last div whose id begins with dataTes
//remember we have id like dataTes1,dataTes2 etc
if($("div[id^=dataTes]").length==1){
//check if only one element is present
$("#remove").hide();//if yes hide the remove button
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<legend>Test</legend>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="remove" value="-" style="display:none;" title="#">
<!--hide the remove button with display:none initially-->
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="sub" value="-" title="#">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table id="dataID" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Explained line by line as comments. Do let me know if this confuses you.
1) Rename the duplicate IDs on the buttons (originally both id="button").
<input type="submit" class="button" id = "button_duplicate" value="+" onlick="duplicate()" title = "#">
<input type="submit" class="button" id = "button_remove" value="-" onlick="remove()" title = "#">
2) Bind the duplicate() and remove() functions on correct buttons. Instead of the document.getElementById('button').onclick = duplicate;
$("#button_duplicate").click(function(){
duplicate();
});
$("#button_remove").click(function(){
remove();
});
3) The remove function:
function remove(){
if($("#dataTes" + i).length > 0){
$("#dataTes" + i).remove();
i--;
}
}
value of i will be in the context. So you can get the id of the element and remove it. Then decrement i. Try this:
EDIT(corrected code):
function remove(){
var elId = "dataTes" + i;
var element = document.getElementById(elId);
element.parentNode.removeChild(element);
i--;
}
also first, you need to change id of the button in your html code.
<input type="submit" class="button1" id = "add" value="-" onClick="deleteRow('#')" title = "#">
and in javascript, it should be:
document.getElementById('button').onclick = duplicate;
document.getElementById('button1').onclick = remove;

Clear all input text box vale at append time

What I want is that when I click on add more, append all text box with blank value add more function is properly working but at the time of appending input box append with value but I want to clear text box value.
<table>
<tbody>
<tr class="topdivdata">
<td> <input type="text" value="First Name"></td>
<td> <input type="text" value="Last Name"></td>
<td> <input type="text" value="Mobile Number"></td>
</tr>
<tr role="row" class="odd">
<td>
<span class="btn btn-xs cic" id="addnewunit">
<i class="icon-plus"></i>+ Add More</span>
</td>
</tr>
</tbody>
<tbody id="addmoreunit"></tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script>
unitcount=1;
$('#addnewunit').click(function()
{
var topdiv = $('.topdivdata').html();
var refresdiv=topdiv;
$('#addmoreunit').append('<tr>.'+refresdiv+'.<td class="removes1"><span class="btn btn-xs"><i class="icon-plus"></i>- Remove</span></td></tr>');
unitcount++;
var value = $('.target').val();
$('.list').val(value);
$('.removes1').click(function()
{
$(this).parent().remove();
});
});
</script>
i want to when i click on add more append all text box with blank value add more function properly working but at append time input box upend with value but i want to clear text box value
<table>
<tbody>
<tr class="topdivdata">
<td> <input type="text" value="First Name"></td>
<td> <input type="text" value="Last Name"></td>
<td> <input type="text" value="Mobile Number"></td>
</tr>
<tr role="row" class="odd">
<td>
<span class="btn btn-xs cic" id="addnewunit">
<i class="icon-plus"></i>+ Add More</span>
</td>
</tr>
</tbody>
<tbody id="addmoreunit"></tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script>
unitcount=1;
$('#addnewunit').click(function()
{
var topdiv = $('.topdivdata').html();
var refresdiv=topdiv;
$('#addmoreunit').append('<tr>.'+refresdiv+'.<td class="removes1"><span class="btn btn-xs"><i class="icon-plus"></i>- Remove</span></td></tr>');
unitcount++;
var value = $('.target').val();
$('.list').val(value);
$('.removes1').click(function()
{
$(this).parent().remove();
});
});
</script>
not understand your question, but you can do like these,
<table>
<tbody>
<tr class="topdivdata">
<td>
<input type="text" value="First Name">
</td>
<td>
<input type="text" value="Last Name">
</td>
<td>
<input type="text" value="Mobile Number">
</td>
</tr>
<tr role="row" class="odd">
<td>
<span class="btn btn-xs cic" id="addnewunit" style="cursor:Pointer;">
<i class="icon-plus"></i>+ Add More
</span>
</td>
</tr>
</tbody>
<tbody id="addmoreunit"></tbody>
</table>
and script is like,
var unitcount = 1;
$('#addnewunit').click(function () {
//Here i cloned your topDiv, so that i can add new inputs.
var CloneTopDiv = $('.topdivdata').clone(true);
CloneTopDiv.find(':input').attr('value', '');
CloneTopDiv.attr('class', 'txtInput')
CloneTopDiv = CloneTopDiv.html();
var refresdiv = CloneTopDiv;
$('#addmoreunit').append('<tr>.' + refresdiv + '.<td class="removes1"><span class="btn btn-xs" style="cursor:Pointer;"><i class="icon-plus"></i>- Remove</span></td></tr>');
unitcount++;
var value = $('.target').val();
$('.list').val(value);
//Code for Remove added row
$('.removes1').click(function () {
$(this).parent().remove();
});
//Clearing Code
$('.txtInput').val('')
});
See solution at https://jsfiddle.net/eua98tqa/3/

Categories

Resources