Below is my javascript function to add new row to <table> in HTML. I need a unique row id for each table row. Below is my code :
$(document).ready(function(){
var html = '<tr><td class="cb"><input class="form-control" type="text" value="" id="inputString" name="inputString"/><div id="showList"><ul class="list-group"></ul></div></td><td><input type="checkbox" name="debit" class="form-control"></td><td><input type="checkbox" name="credit" class="form-control"></td><td><input type="number" name="amount" class="form-control"></td><td><input class="btn btn-warning" type="button" name="remove" id="remove" value="Remove" onclick="removeMe(this);"></td></tr>';
var x=1;
$("#add").click(function(){
$("#table_field").append(html);
});
});
How can I achieve this in the same function
I tried creating unique ids but not able to do.. Please help me
I need a unique row id for each table row.
To add an id to each row while adding you just have to pass it on $("#table_field").append(). Below I am using the length of tr inside #table_field to set an id.
$("#add").click(() => {
const
tTable = $("#table_field"),
tID = `tr${tTable.find('tr').length}`;
tTable.append(
`<tr id = '${tID}'><td>${tID}</td></tr>`
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id = 'table_field'></table>
<button id = 'add'>Add</button>
You can adjust the logic of generating the id to how you see fit. Like using Math.random or Date ticks.
Related
I am trying to get respective values of dynamically generated inputs. In other words, I have an X number of dynamically generated inputs; each of these inputs is bound to a button. With that being said, I would like the user to get alerted the dynamically generated input that is bound to the clicked button. What I have done so far does not sort this out and whatever button is clicked, only the first input's value is generated.
I have the following code - a dynamic input and a button:
<input type="hidden" id="job_id" name="jobIdName" value="{{ job_id }}"> // please note this input is dynamically generated....
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
As for Jquery, I have done the following:
$('#get_id_id').each(function(index) {
$(this).click(function() {
var job_ids = $("[name='jobIdName']");
console.log('Job Ids -------------- : ' + job_ids);
});
});
The above code keeps generating only the first generated input value? Any ideas or suggestions?
I have seen some posts that might seem similar to this one but they are very old; also I am looking for a more modern implementation.
Add your "input tag" into div:
var counter = 0;
$(document).ready(function(){
$("#get_id_id").click(function() {
var divChildren = $(".job_ids").children();
if(counter < divChildren.length){
if(counter == '0'){
console.log($(divChildren).eq(0).val());
}else{
console.log($(divChildren).eq(counter).val());
}
counter++;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="job_ids">
<input type="hidden" name="jobIdName" value="Test01">
<input type="hidden" name="jobIdName" value="Test02">
<input type="hidden" name="jobIdName" value="Test03">
<input type="hidden" name="jobIdName" value="Test04">
<input type="hidden" name="jobIdName" value="Test05">
</div>
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
I am using jQuery to add and remove table rows for a collection of forms within another form in Symfony 4. This was not easy, but eventually made it work. With a macro in Twig I can get this rendered result:
<table>
<div id="document-list" data-prototype="
<tr>
<td>
<fieldset class="form-group">
<div id="program_programDocument___name__" novalidate="novalidate">
<div class="form-group"><input type="text" id="program_programDocument___name___name" name="program[programDocument][__name__][name]" required="required" class="form-control"/>
</div>
</div>
</fieldset>
</td>
<td>
<button type="button"class="remove-collection-widget"data-list="#remove-collection-widget">Remove</button>
</td>
</tr>" data-widget-tags="<div></div>">
</div>
</table>
<button type="button" class="add-another-collection-widget" data-list="#document-list">Add document</button>
I cleaned up this code as much as possible to make it readable. All the HTML within data-prototype="...." is how it should be. My code works (ish) together with some jQuery:
jQuery('.add-another-collection-widget').click(function(e) {
var list = jQuery(jQuery(this).attr('data-list'));
// Try to find the counter of the list or use the length of the list
var counter = list.data('widget-counter') | list.children().length;
// grab the prototype template
var newWidget = list.attr('data-prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newWidget = newWidget.replace(/__name__/g, counter);
// Increase the counter
counter++;
// And store it, the length cannot be used if deleting widgets is allowed
list.data('widget-counter', counter);
// create a new list element and add it to the list
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
$(function() {
$(document).on("click", ".remove-collection-widget", function() {
$(this).closest("tr").remove();
});
});
The problem is, the rendered result when added more form rows is that they don't actually end up within the table. You can see for yourself (JSFiddle) the result looks alright, but in reality it's not.
I am pretty sure it has to do with my jQuery, but I am stuck now and hope some of you can point out what is wrong.
Putting a div as a direct child of a table isn't proper HTML, which is what's tripping it up.
Move id="document-list" data-prototype="... to table element
Get rid of div inside table
Change data-widget-tags to tr instead of div
Remove wrapping tr from data-prototype
Solution
jQuery('.add-another-collection-widget').click(function(e) {
var list = jQuery(jQuery(this).attr('data-list'));
var counter = list.data('widget-counter') | list.children().length;
var newWidget = list.attr('data-prototype');
newWidget = newWidget.replace(/__name__/g, counter);
counter++;
list.data('widget-counter', counter);
var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget);
newElem.appendTo(list);
});
$(function() {
$(document).on("click", ".remove-collection-widget", function() {
$(this).closest("tr").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="document-list" data-prototype="
<td>
<fieldset class="form-group">
<div id="program_programDocument___name__" novalidate="novalidate">
<div class="form-group"><input type="text" id="program_programDocument___name___name" name="program[programDocument][__name__][name]" required="required" class="form-control"/>
</div>
</div>
</fieldset>
</td>
<td>
<button type="button"class="remove-collection-widget"data-list="#remove-collection-widget">Remove</button>
</td>" data-widget-tags="<tr></tr>">
</table>
<button type="button" class="add-another-collection-widget" data-list="#document-list">Add document</button>
Documentation
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table (see Permitted Content)
I have a form with this filed and by ADD button I can add rows: book_date[], book_desc[], book_pages[].
<form method="POST" action="addpages.php" name="books" onmouseover="javascript:sum();">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<table id="dataTable" class="form">
<input type="text" class="form-control" name="date_book[]">
<input type="text" class="form-control" name="book_pages[]">
<input type="text" class="form-control" name="book_pages_total">
</table>
</form>
When add a new row I want the value inside the first filed date_book was copyed in the new row.
I try ti use this start script, but this not work for new row.
var $date_book= $("#date_book[]");
$date_book.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $date_book[].val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$date_book[].val(v1);
v2 = v1;
}
};
How to copy the date values write in in the filed date_book[] in each new row?
I hope to explain my problem.
Thanks
You should start with valid HTML, an input can't be a child of a table. I've just mocked–up something based on the names.
After fixing that, in POJS you can just clone the last row and add it to the table. That will also clone whatever values the form controls happen to have at the time, so if you only want to keep the first value, then do that and clear the others, e.g.
function addRow(tableId) {
var table = document.querySelector('#' + tableId);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {if (i) input.value = '';});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
<form name="books">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td><input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td><input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td><input type="text" class="form-control" name="book_pages_total">
</table>
</form>
I'm trying to append an HTML string to
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$('#featureContainer').append(jfield);
When the button is clicked it will crete a input field, but if I click again it creates the input in the same row.
How can I make a new row with the input in it?
The following is my HTML code
<tr>
<td id="featureContainer"></td>
</tr>
If I click the button for the second time it creates it in the same row.
I want it to create it in new row.
As we don't know wether trs are wrapped inside table or tbody, .... We have to look for the closest tr and then get its parent then append a new row to that parent.
So, you should replace this:
$('#featureContainer').append(jfield);
with:
$('#featureContainer').closest('tr').parent().append('<tr><td>' + field + '</td></tr>');
NOTE: that inside field you have a static ID which will be on all the inputs you spawn which will be wrong since IDs are unique. So you may want to assign diferent IDs for diferent inputs.
You can just add the html code into field variable, like below:
var field = "<tr><td id="featureContainer"><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td>
</tr>"
var jfield = $(field);
Assuming there is a button with id = 'add' and a table with id='data', then you can add this after above code:
$('#add').click(function(){
$('#data').append(jfield);
});
Your on the right track. But you don't need the jfield.
this appends the value of 'field' inside the td element:
$('#featureContainer').append(field);
but what you want is to append inside the table. So give your table a id (or the tbody) and do the following:
You need to embed the field inside a <tr><td> section and append that as a whole.
var field = var field = '<tr><td><input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value=""></td></tr>';
then in the click event:
$('#tableid').append(field);
Thr issue with your code is that you are trying to append to an element using id selector. Since in a valid html there should be only a single element with an unique id, you will be appending the new element always to the same td#featureContainer.
I will suggest you to change the id to class. To select the td.featureContainer where you need to append the new element, you can check inside the clicked button element event handler and find the td.featureContainer
$(".feature").on("click", function() {
var field = '<input type="text" name="featureName" class="form-control" id="featureName" placeholder="Feature Name" value="">'
var jfield = $(field);
$(this).parent().prev(".featureContainer").append(jfield);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row one">
</td>
</tr>
<tr>
<td class="featureContainer"></td>
<td>
<input type="button" class="feature" value="click for row two">
</td>
</tr>
</table>
First the id should be unique in the same document so better to use a common classes instead, then you could use append() to add new row (including tr/td), check the example below.
Hope this helps.
$('#add-row').on('click', function(){
var field = '<input type="text" name="featureName" class="form-control" placeholder="Feature Name" value="">'
$('table').append('<tr><td>'+field+'</td></tr>');
console.log($('table tr').length+' rows');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Default row</td>
</tr>
</table>
<button id='add-row'>Add row</button>
I want to be able to append an additional row to my table. The way the code is now, it just adds two input boxes outside of the table regardless of where I insert it. When I inspect in my browser, it looks like the table tags have been stripped, is there something wrong with using the getElementByID function?.
My Hidden row to be added to the table:
<div id="rowToBeAdded" style="display: none">
<tr>
<td><input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /></td>
<td><input style="margin-right:2em;" type="text" value="" name="newLinkTitle[]" size="50" /></td>
<td><input type="text" value="http://" name="newLinkAddress[]" size="50" /></td>
</tr>
</div>
After the last </tr> of my table I have:
<span id="addRowHere">
<input type="button" id="moreFields" value="Add more links" onclick="init()" />
</span>
And here's my Javascript:
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
var newFields = document.getElementById('rowToBeAdded').cloneNode(true);
newFields.style.display = 'block';
var newField = newFields.childNodes;
var insertHere = document.getElementById('addRowHere');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
Try this
http://jsfiddle.net/blackjim/yGVWM/3/ EDIT: fixed the remove button
document.getElementById('moreFields').onclick = addMoreFields; // set binding
var newRow = document.getElementById('rowTemplate').cloneNode(true),
myTable = document.getElementById('myTable');
function addMoreFields() {
myTable.appendChild(newRow.cloneNode(true));
}
And you should make a function for removing a line also. Try it yourself. And use classes and id to get your elements.