Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to create a table using jquery. The number of rows the table will be determined from input box. The number of columns are known. After submitting that, a table gets generated. Tried creating a fiddle.
Am very new to jquery . Not sure how to proceed.
Fiddle link here
<form>
Number of rows to be generated
<br>
<input type="number" id="table-row-num" value="3">
<button>Submit</button>
</form>
<div id="table-gen">
<p>Table generated here after clicking submit</p>
<table cellpadding="1" cellspacing="1" border="1">
<tr>
<td>1</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>3</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
</table>
</div>
This is your fiddle updated:
http://jsfiddle.net/fpd8dwtw/17/
This is the jquery code:
$("#submitButton").click(function() {
var table = $("#resultTable");
var rowNum = parseInt($("#table-row-num").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
I wish you luck with implementation. :)
Edit:
If you want to allow number of rows to be on range between minimum and maximum number the best solution is to use native html 5 validation.
This is jsfiddle:
http://jsfiddle.net/fpd8dwtw/20/
Say you gave an id to your <table> element
<table cellpadding="1" cellspacing="1" border="1" id="tableElement">
and an onclick attribute to your button
<button onclick="addRows()">Submit</button>
your (pure) Javascript should look like this :
function addRows() {
var table = document.getElementById('tableElement');
var rows = parseInt(document.getElementById('table-row-num').value);
for (var i = 1; i <= rows; i++) {
var tr = document.createElement('tr');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var input1 = document.createElement('input');
var input2 = document.createElement('input');
input1.type = "text";
input2.type = "text";
input1.placeholder = "Text goes here...";
input2.placeholder = "Text goes here...";
cell1.innerHTML = i.toString();
cell2.appendChild(input1);
cell3.appendChild(input2);
tr.appendChild(cell1);
tr.appendChild(cell2);
tr.appendChild(cell3);
table.appendChild(tr);
}
}
Now I'm sure the jquery code would be a lot smaller but trust me, your browser would respond a lot faster to pure Javascript.
you can use append of jQuery.
var count = 30;
var row = "<tr><td>1</td><td>2</td><td>3</td></tr>";
for(var i=0; i< count; i++){
$('#tableId tbody').append(row);
}
<table id="tableId"></table>
I have created a fiddle for you. Have a look
https://jsbin.com/hoyetu/edit?html,js,output
$('button').on('click', generate);
function generate(e) {
var rows = $('#table-row-num').val();
var html = '';
for (var i = 0; i < rows; i++) {
html += '<tr>' +
'<td>' + (i + 1) + '</td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'</tr>';
}
$('table').html(html);
}
http://jsfiddle.net/fpd8dwtw/13/
$("#createTable").on("click", function (event){
event.preventDefault();
var noOfRows = $("#table-row-num").val();
var noOfCols = 3; // fixed columns as you mentioned in the question
var fragment = document.createDocumentFragment();
var oTable = document.createElement("table");
for(var i =0; i < noOfRows; i++){
var oTr = document.createElement("tr");
for(var j=0; j < noOfCols; j++){
var oTd = document.createElement("td");
oTd.innerHTML = "put your content here";
oTr.appendChild(oTd);
}
oTable.appendChild(oTr);
}
$("#table-gen").html(oTable);
});
Related
I have a script to generate a 10 character code when a button is clicked. I want to transplant the code into the value field of a input text-box. I believe there is a conflict because the text-box is within a form that has a click(function(event) { attached.
HTML/CSS
<div id="add_wrap">
<form method="post" action="voucher_add_post.php">
<table width="100%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td>Voucher value: </td>
<td><input type="text" id="value" size="10"></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" id="code" size="20"> <button id="generate">Generate</button></td>
</tr>
<tr>
<td>How many vouchers?</td>
<td><input type="text" id="amount" placeholder="Leave blank for only one voucher" size="40"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
</form>
<div id="message"></div>
</div>
Javascript/JQuery
<script>
$("#submit").click(function(event) {
event.preventDefault();
var headline = $('#headline').val();
var author = $('#author').val();
var details = $('#details').val();
var question = $('#question').val();
var reward_img = $('#reward_img').val();
var reward_cap = $('#reward_cap').val();
var days = $('#days').val();
$.ajax({
type: "POST",
url: "pages/comp_add_post.php",
data: "headline="+headline+"&author="+author+"&details="+details+
"&question="+question+"&reward_img="+reward_img+"&reward_cap="+reward_cap+"&days="+days,
success: function(data){
$("#message").html(data);
}
});
});
$("#generate").click(function(event) {
event.preventDefault();
function codeGen(length)
{
var code = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));
return code;
}
$("#code").val(codeGen(10));
});
</script>
The problem is it only generates a single character into the value= attribute of the input box with an ID of generate.
If I use the onClick="codeGen()" method of doing it, then it submits the form.
I think the issue is in your for loop. You currently have it written as:
for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));
But the ; after the for loop declaration terminates the statement. If you rewrite it as:
for (var i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
It seems to work.
Fiddle: https://jsfiddle.net/s3ndkpue/
The for loop with the semi colon is the issue, however I would also try and simplify the JS + Jquery so it is easier to read as below:
$("#generate").click(function(event) {
event.preventDefault();
var code = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i=0; i < 10; i++)
code += chars.charAt(Math.floor(Math.random() * chars.length));
$("#code").val(code);
});
Hope that helps :)
Here I am trying to store medicines given by doctor via html form.
By taking an input as text in cells of a dynamic table, I want to append some counter to the name tag of the input cell by using javascript but unable to do so.I want to create new input tag with attr name as prsc+counter-value
so can u please help me
<table id="myTable">
<tr>
<td><input type="text" name="prsc0"></td>
</tr>
<tr>
<td><input type="text" name="prsc1"></td>
</tr>
<tr>
<td><input type="text" name="prsc2"></td>
</tr>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
<script>
var counter=3;
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
counter=counter+1;
var presc="prsc"+""+counter;
cell1.innerHTML = '<input type="text" name=presc>';
}
function myDeleteFunction() {
document.getElementById("myTable").deleteRow(0);
}
</script>
Your presc is a variable:
cell1.innerHTML = '<input type="text" name="' + presc + '">';
or without creating it:
cell1.innerHTML = '<input type="text" name="presc' + counter + '">';
JSBin
Use the DOM API to create the input element instead of building an HTML string:
var input = document.createElement('input');
input.name = 'prsc' + counter;
cell1.appendChild(input);
function counter (){
for(i=0; i<document.querySelectorAll('input').length; i++){
document.querySelectorAll('input')[i].name=`prsc${i}`;
}
}
When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.
This is for generating the table.
function makeTable()
{
var row_num = 20;
var cell_num = 4;
var tab = document.createElement('table');
tab.setAttribute('id','newtable');
var tbo = document.createElement('tbody');
tbo.setAttribute('id','tabody');
var cont;
for(var c = 0 ; c < row_num ; c++)
{
var row = document.createElement('tr');
for(var k = 0 ; k < cell_num ; k++)
{
var cell = document.createElement('td');
if (k > 0)
{
cont = document.createElement("input");
cont.setAttribute('type','text');
}
else
{
cont = document.createTextNode("0" + (c+1));
}
cell.appendChild(cont);
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
document.body.appendChild(tab);
tab.setAttribute("align", "top-left");
}
This function is used to show the data in alert box but I want to retrieve document.getElementById('hide').value............
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hide').value = str;
I want to retrieve only this hidden control (i.e-"hide") in php.
alert(document.getElementById('hide').value);
}
window.onload = function()
{
makeTable();
};
</script>
</head>
<body>
<h1><u>PROJECT</u> :</h1>
<input type="button" value="Alert" onclick = "GetCellValues()">
I want to retrieve this id in php
<input type="hidden" id="hide" /> <br />
<div id="mytable">
<table id = "project" border = "1" width ="60%" class = "newtable" cellpadding="10" cellspacing="0">
<tr>
<th align="center" width ="200px">Sl.No.</th>
<th align="center" width ="200px">Project Name</th>
<th align="center" width ="200px">ChangeDate</th>
<th align="center" width ="200px">Changed By</th>
</tr>
</table>
</div>
</body>
Note: I want to retrieve the hidden control through id in php ##
I want the total php code to retrieve this hidden control data(i.e-input type="hidden" id="hide") because I'm a beginner
You have to add a name to your input so for example:
<input type="hidden" id="hide" name="foo" />
To retrieve the value in php after POST form submission you can do this:
<?php $var1 = $_POST["foo"]; ?>
Can you please replace this line
<input type="hidden" id="hide" />
to
<input type="hidden" id="hide" name="hide" />
and use $_POST["hide"] in you php script.
Input field must have some name to access it
<input type="hidden" id="hide" name="hide" />
do normal fetch
$name = $_POST['hide'];
add name property to input type and value you want to get into you php
<input type="hidden" id="hide" name="flag" value="1" />
and to retrieve the value in php after POST form
$var1 = $_POST["flag"];
I am having a table it contains only one row. Row has a lot of elements like textboxs and buttons. When I click the button the table row will be cloned using append() function. My problem is when I click the button I want to increment the textbox and button id. How can I do this?
Example HTML:
<tr id="items:1">
<td id="id">
<input type="text" id="price:1" name="price" value="" size="6" readonly="readonly" />
</td>
<td id="id">
<input type="text" id="quantity:1" name="quantity" size="10" align="middle" onblur="totalprice(this)" />
</td>
<td id="id">
<input type="text" id="total:1" name="total" size="10" value="0" readonly="readonly" align="middle" />
</td>
<td id="id">
<input type="button" onclick="cloneRow()" id="button:1" value="ADD" />
</td>
</tr>
Example JavaScript:
function cloneRow() {
var row = document.getElementById("items:1");
var table = document.getElementById("particulars");
var clone = row.cloneNode(true);
var rowId = "items:" + a.toString();
clone.id = rowId;
var tabledataid = document.getElementById("id");
var inputtext = tabledataid.getElementsByTagName("input");
var inputtextid = inputtext[a];
var changeInputTextid = "price:" + b.toString();
inputtextid.id = changeInputTextid;
alert(changeInputTextid);
table.appendChild(clone);
a++;
}
A fiddle
Create a function to add rows and just use the indexes of text boxes and columns correctly
function insertRow() {
var x = document.getElementById('ttable');
var new_row = x.rows[0].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
x.appendChild(new_row);
}