Home › Forums › JavaScript › JS Add/Remove Row in Table
- This topic is empty.
-
AuthorPosts
-
August 26, 2013 at 12:34 pm #148179
bmoneruiux
ParticipantHey guys.
Trying to do a mockup for my company, but I’m not yet anywhere near advanced enough to do what I envision, so hopefully I can get some help.
I understand the basics of JS, however in my specific case I’m unaware of how to code an “add/delete row” for this. All other tutorials and examples don’t address my specific needs.
Here’s the link to the project on CodePen
Basically when someone clicks the plus button, a brand new row should populate at the bottom with the same content as “.pt-entry” BUT with the new row incrementing 1 unit. So the row created under “.pt-entry” will then be called “.pt-entry-1” (since the first would technically be 0), and so forth.
And the reverse should happen with the delete button. When pressed, the row it corresponds to should delete. However if only 1 row remains, it cannot be deleted. Only cleared of data. If the delete button is press on one remaining row, an alert window should show saying something like “Cannot delete last remaining row. Clear data fields instead? Yes/No”.
I would like for this to be in standard JavaScript and not jQuery or any other type of JS library.
August 27, 2013 at 7:24 am #148227cav_dan
ParticipantSo, I’m still kind of a noob on JS, but you may want to use jQuery here.
First things first: you really shouldn’t use tables for anything other than tabular data, I would try using divs and whatnot. But, since you may have your own reasons, let’s start.
You’ll need is get the code for that row in a string, and the data you want to change in variables. Something like:
var formIndex = 1;
var newRow = '<tr><td>Some content<tr><td>'
newRow += '<td><textarea id="'+formIndex+'"></textarea>';Then, you can use jQuery’s append
$('.emptyDiv').append(newRow)
to include that new code, not forgetting to increase that indexformIndex+= 1
August 27, 2013 at 7:44 am #148229Willson
ParticipantCheck out this pen I made: http://codepen.io/WillsonSmith/pen/cLktj
//Define your elements var table = document.getElementById('theTable'), // your parent element you are adding content to rows = table.querySelectorAll('tr'), //initial rows for counting rowCount = rows.length, //how many rows exist addedRow = document.createElement('tr'), //create the new row addButton = document.getElementById('add'), removeButton = document.getElementById('remove'); //basic buttons for example function addRow(){ var thisRow = addedRow.cloneNode(true); //clone your created row thisRow.setAttribute('class','.pt-entry-' + rowCount); //set the class to be class + the row count (will increment) rowCount += 1; //increment thisRow.innerHTML = '<td>row</td>'; //adding whatever, not necessary table.appendChild(thisRow); //puts the row in to your parent } function removeRow(){ var items = table.querySelectorAll('tr'); //get the new list of rows if (rowCount > 1){ table.removeChild(items[rowCount - 1]); } //remove the last item rowCount -= 1; //decrement } addButton.addEventListener('click', function(e){ addRow(); }); removeButton.addEventListener('click', function(e){ removeRow(); });
Since you’re only adding one element at a time, this is probably the way to do it. I didn’t look it over too much for optimisations because they would most likely be very small ones that really wouldn’t affect your code.
Note that if you were adding multiple items in to the dom at once, you would want to create a document fragment that you applied all of your added nodes to, and then apply the fragment to the page.
see: https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment
edit: added a check to make sure it’s not removing the last row
August 27, 2013 at 9:19 am #148236TheDoc
MemberI would like for this to be in standard JavaScript and not jQuery or any other type of JS library.
You’re not proficient enough in JavaScript to do it yourself and are asking people to do it for you but you refuse to use the help of jQuery? Seems a bit backwards to me.
August 27, 2013 at 10:49 am #148248bmoneruiux
ParticipantYou’re not proficient enough in JavaScript to do it yourself and are asking people to do it for you but you refuse to use the help of jQuery? Seems a bit backwards to me.
Ok, I feel stupid. So I’m currently in the middle of learning jQuery (Yes, without having learned raw JavaScript first…I know). I wasn’t sure if the CMS my job created used jQuery, so I figured JavaScript would be a safe bet for now. I don’t know why i didn’t look at the course code, but there it is in the header…calling v1.8.6. So…I guess I could’ve used jQuery all along…
Now…you may commence chastising me for learning jQuery before actual JS :(
August 27, 2013 at 10:54 am #148250bmoneruiux
ParticipantFirst things first: you really shouldn’t use tables for anything other than tabular data, I would try using divs and whatnot. But, since you may have your own reasons, let’s start.
Trust me, I know lol. I, for one, hate tables. But the tool that this is based off of is already created, used by our team and our team alone, and I was given strict orders to not alter the structure of the tool just the function of it 0_o (confusing I know).
I wish I could post a snippet of the source without losing my job lol.
August 27, 2013 at 3:09 pm #148283TheDoc
MemberNow…you may commence chastising me for learning jQuery before actual JS :(
No chastising! I actually think jQuery is a fantastic learning tool. It’s where I started as well.
September 4, 2013 at 7:40 am #149007bmoneruiux
ParticipantOK…here’s my latest effort!
September 4, 2013 at 10:47 am #149028cav_dan
ParticipantNice job!
Ok, there’s surely room for improvement. For example: why did you use
$('body').on('click', 'myClass' ...)
when you could simply use$('.myClass').on('click' ...)
?Also, when hidding part of your form, you could use a better selector for turning those inputs ‘readonly’. Maybe use
$('#' +i+ ' input')
or some other solution like that (I’m not being specific here, just think you can work something out in the future).September 4, 2013 at 10:58 am #149031bmoneruiux
ParticipantMy syntax MIGHT have been wrong (very sure actually), but when I tried it like that…the function with the alert stopped working. And yeah I was hoping for a better ‘readonly’ solution. However I’ll leave this to more experienced coders when i hand the demo over.
FYI I was LITERALLY learning while I was coding lol
September 4, 2013 at 11:45 am #149035cav_dan
ParticipantHey man,
I’m not trashing your code, just pointing some stuff out. I’m still learning too, and you seem ahead of me in many ways. Sorry if I sounded a bit rude, it wasn’t my intention.
September 4, 2013 at 11:59 am #149037bmoneruiux
Participant… I’m not trashing your code, just pointing some stuff out. I’m still learning too, and you seem ahead of me in many ways. Sorry if I sounded a bit rude, it wasn’t my intention.
Oh no you weren’t rude at all lol.
I was saying that since I’m the definition of a newb, my syntax was probably dead wrong when I attempted to implement what you suggested. I was confirming what you were saying. So, sorry if “I” came off as confusing.:D
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.