How to set value in dynamically added rows form using jquery? - javascript

I have a form in php with dynamically added rows (after clicking button the row is added). I want to fill the field with value "xx" and i want to do it in jquery.
This loop create the dynamically added rows in jquery. I want to fill added fields with value "xx":
while($personsArrayLength>2){
echo '
<script>
$(document).ready(function(){
var i = 2;
var rowTemplate2 = jQuery.format($("#template2").html());
rowTemplate2.value = "xx";
addRow2();
function addRow2(){
var ii = i++;
$("#app_here2").append(rowTemplate2(ii));
$("#delete_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
});
</script>
';
Here is html for that:
function addRows2(){
global $personsError_css;
$personsArray = $_POST['persons'];
JB_var_dump($_POST['whichRow']);
$html = '<table id="template2" align="right" style="display:none; ">
<tr id="row_{0}">
<td><input type="text" size="52" id="persons" name="persons[]" maxlength="100"></td>
<td><img src="/../_img/row_del.png" id="delete_{0}" alt="usun"></td>
</tr>
</table>
<table id="list2" style="margin-left:200px;">
<thead >
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" size="52" name="persons[]" maxlength="100" style="'.$personsError_css.';" value="'.$personsArray[1].'"></td>
<td></td>
</tr>
<tr>
<td colspan="2" id="app_here2"></td>
</tr>
</tbody>
</table>';
return $html;
}
This is properly filled form
In this epty fields I want to add values "xx"
Sorry for my english.
How can i set values in added rows? What i should change in my code?
Thanks for help.

Change your 'addRow2' to this:
function addRow2(){
var ii = i++;
$("#app_here2").append(rowTemplate2(ii));
//UPDATE: var rowTemplate2 is not a jQuery Object, as i thought
$("#template2").find("input:empty").val("xx");; // added this row
$("#delete_" + ii).click(function(){
$("#row_" + ii).remove();
});
}

Related

How to get all values inside HTML table using JQuery

I have a table which looks like below and i want to get all values inside the table including the value of text box and check box.
<div class="container-fluid">
<h1 class="h3 mb-4 text-gray-800"><?= $title; ?></h1>
<div class="container" style="text-align: left">
<table class="table table-sm" id="tbl">
<thead>
<tr>
<th>No</th>
<th>Checklist Item</th>
<th>Cheklist</th>
<th>Actual</th>
<th>Recomended</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">1</td>
<td>Check and clean rubber roller cage</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">2</td>
<td>Tension Rod all </td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">3</td>
<td>Delete all unnecessary file from system</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
save
</div>
when i grab all value using this script i cant get value inside the text box and checkbox
$(document).on('click', '#save', function() {
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
var myObj = {
"Array": myRows
};
alert(JSON.stringify(myObj));
});
I want to convert it to JSON but the value of text box and check box not shows inside table. Kindly help me to resolve this issue.
Thank you in advance.
You can find the input and use .val() to get its value if the table cell's text is empty. Checkboxes and text inputs will need to be handled separately.
const text = $(this).text();
if(text){
myRows[index][headersText[cellIndex]] = text;
} else {
const input = $(this).find('input');
if(input.is(":checkbox")){
myRows[index][headersText[cellIndex]] = +input.prop('checked');
} else {
myRows[index][headersText[cellIndex]] = input.val();
}
}

Unable to get data from the second column of a table on clicking of the button in third column

I have a table which has four columns second being a paragraph field , the third being an input field and fourth being a button . What i want is on clicking of the button row the data from the paragraph column should be applied to the input field i.e third row .
Its not possible to select every row using each function as every row is different and theres only few rows like this . How can this be done
I have tried this but it didn't work
var or1 = $("#tab_logic button");
or1.each(function() {
$(this).click(function(){
alert("u");
var u = $(this).parent("tr").find('td:first').html();
alert(u);
});
});
Without knowing the exact HTML, I made this based on your explanation. If I understand correctly, this is what you want to achieve?
$("button").click(function() {
var row = $(this).closest("tr");
var name = row.find("p").html();
var input = row.find("input");
input.val(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Input</th>
<th>Button</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td><p>John Doe</p></td>
<td><input type="text" placeholder="Name"/></td>
<td><button type="button">Set name</button></td>
</tr>
<tr>
<td>1</td>
<td><p>Jane Doe</p></td>
<td><input type="text" placeholder="Name"/></td>
<td><button type="button">Set name</button></td>
</tr>
</tbody>
</table>
Another solution would be
var or1 = $("#tab_logic button");
or1.each(function() {
$(this).click(function() {
var text = $(this).closest('tr').children('td:eq(1)').children().first().html();
$(this).closest('tr').children('td:eq(2)').children().first().val(text);
});
});
#tab_logic td{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tab_logic">
<tr>
<td>one</td>
<td><p>I'm just a paragraph</p></td>
<td><input type="text"/></td>
<td><button>button</button></td>
</tr>
<tr>
<td>two</td>
<td><p>I'm just another paragraph</p></td>
<td><input type="text"/></td>
<td><button>button</button></td>
</tr>
</table>

function getelementbyid not outputting to correct place

I am making a form to add players into an event.
The form searches a db of players with search criteria specified by the user and then lists all matching players with an add button next to them.
I also have a table with all the table headers done and then a
<div id="PlayerAdded">
tag before the end of the table.
I have written a function to output the data for the next row to the table when a players "Add" button is clicked. My function says:
function add(){
document.getElementById("PlayerAdded").innerHTML += "<tr><td>success</td></tr>";
}
I expected this to add a row, but instead it adds just the word "success" above the table (Perhaps I was a little optimistic when I used the word success as my test string lol).
Can someone please tell me why it is not adding the code inside the div "PlayerAdded"?
If it helps, here is some of the HTML:
<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?></th></tr>
<tr><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th></tr>
<div id="PlayerAdded"> </div>
<tr><td colspan='3'>Search <input type='text' id='newsearch'></input>
</table>
There were a couple of problems with your existing HTML - which therefore broke your DOM when the browser attempted to assemble things.
a <div> element – in a <table> – must be contained within either a <th> or <td> element; no other element is a valid child of a <tr> element, and the only valid children of a <table> element are <thead>, <tfoot>, <tbody> and <tr> elements.
neither your last <tr>, or its child <td>, element were closed – the browser will automatically close these elements when it encounters another <td> (since neither a <td>, nor a <tr>, can be directly nested within another <td>).
That said, I'd correct your HTML to the following:
<table>
<tbody>
<tr>
<th colspan='6'>« php response »</th>
</tr>
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr>
<td colspan='3'>Search
<input type='text' id='newsearch' />
</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNewRow">Add a new row</button>
And your JavaScript to the following:
function addNewRow() {
// creating the relevant elements to be added:
var row = document.createElement('tr'),
td = document.createElement('td');
// setting the text of the created-<td> element:
td.textContent = 'Success';
// setting the colSpan property (the colspan attribute):
td.colSpan = '6';
// adding a class-name to the created-<td>, to make it
// visually obvious which are the newly-added <td>
// elements:
td.classList.add('addedRow');
// appending the created-<td> to the created-<tr>:
row.appendChild(td);
// finding the last <tr> of the table, using
// document.querySelector() which will match
// only the first element that matches the
// supplied CSS selector (or null, if no
// element exists that matches):
var lastRow = document.querySelector('table tr:last-child');
// inserting the created-<tr> (and its descendant
// elements parentNode of the lastRow node before
// the lastRow node):
lastRow.parentNode.insertBefore(row, lastRow);
}
// using unobtrusive JavaScript to add the 'click'
// event-listener to the <button> element with the
// id of 'addNewRow':
document.getElementById('addNewRow').addEventListener('click', addNewRow);
function addNewRow() {
var row = document.createElement('tr'),
td = document.createElement('td');
td.textContent = 'Success';
td.colSpan = '6';
td.classList.add('addedRow');
row.appendChild(td);
var lastRow = document.querySelector('table tr:last-child');
lastRow.parentNode.insertBefore(row, lastRow);
}
document.getElementById('addNewRow').addEventListener('click', addNewRow);
table,
td,
th {
border: 1px solid #000;
min-height: 2em;
}
td.addedRow {
font-weight: bold;
text-align: center;
border-color: limegreen;
}
<table>
<tbody>
<tr>
<th colspan='6'>« php response »</th>
</tr>
<tr>
<th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr>
<td colspan='3'>Search
<input type='text' id='newsearch' />
</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNewRow">Add a new row</button>
External JS Fiddle demo, for experimentation or development.
References:
document.createElement().
document.getElementById().
document.querySelector().
Element.classList.
EventTarget.addEventListener().
Node.appendChild().
Node.insertBefore().
Try doing as user #Barmar said:
<script type="text/javascript">
function add(){
var _tr = document.createElement("tr");
var _textNode = document.createTextNode("Success");
_tr.appendChild(_textNode);
var _child = document.getElementById("botTr");
var parentDiv = _child.parentNode;
parentDiv.insertBefore(_tr, botTr);
}
</script>
And then:
<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?> </th></tr>
<tr id="topTr"><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th>
</tr>
<tr id="botTr"><td colspan='3'>Search <input type='text' id='newsearch' />
</table>
<input type="button" name="hitme" id="hitme" value="hitme" onclick="add();" />

incrementing the value of a input field in the cloned row

1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.

Change the value of a text box to its current order in a sortable tab

Edit: I have solved this by myself. See my answer below
I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.
Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. E.g. The text box up the top always has the value of '1', the second is always '2' and so on.
I am using jQuery and the Table Drag and Drop JQuery plugin
Code
Javascript:
<script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
HTML Table:
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td>Pol</td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td>Evo</td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td>Kal</td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td>Lok</td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
Hardnrg in #jquery ended up solving it for me.
It involved adding an id="" to each input:
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr><td>Product</td> <td>Order</td></tr>
</thead>
<tbody>
<tr class="row1" id="Pol"> <td>Pol</td> <td><input id="Pol_field" type="textbox" name="sort1"/></td> </tr>
<tr class="row2" id="Evo"> <td>Evo</td> <td><input id="Evo_field" type="textbox" name="sort2"/></td> </tr>
<tr class="row3" id="Kal"> <td>Kal</td> <td><input id="Kal_field" type="textbox" name="sort3"/></td> </tr>
<tr class="row4" id="Lok"> <td>Lok</td> <td><input id="Lok_field" type="textbox" name="sort4"/></td> </tr>
</tbody>
</table>
</form>
And add this js to the OnDrop event:
for (var i=0; i < rows.length; i++) {
$('#' + rows[i].id + "_field").val(i+1);
}
Easy peasy!
Hmmm..
I think you want to do something like this:
$("input:text", "#table-2").each( function(i){ this.value=i+1; });
The $().each() function's info is here: http://docs.jquery.com/Core/each

Categories