Javascript - removeChild removes a whole cell of a table - javascript

I have table where I can add new rows with input fields. Also there's a possibility to remove an added input field. Deleting a complete row works, but there's a problem to delete single input fields inside a cell.
Here's the code:
cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
var feld = document.createElement("input");
feld.setAttribute("name","avz_keywords" + avz_array + "[]");
feld.setAttribute("onblur","");
feld.setAttribute("type","text");
feld.setAttribute("size","30");
cell1[1].appendChild(feld);
var remove = document.createElement("a");
remove.setAttribute("href","#");
remove.setAttribute("onclick","this.parentNode.parentNode.removeChild(this.parentNode);");
remove.innerHTML = " X";
cell1[1].appendChild(remove);
var br = document.createElement("br");
cell1[1].appendChild(br);
The problem is that the remove action completly deletes the whole cell, instead of the related input field. The strange thing, that this works on the first tier of the table without problems.
Do you see the error? Thanks for any suggestions!

Ok, you are appending the anchor element remove to cell1[1], which is a single table cell of the row with index par.rowIndex. So the parentNode to the anchor element is the cell. With this.parentNode.parentNode.removeChild(this.parentNode) you are removing the parentNode of the anchor, which is the cell.
EDIT: removed a sentence that might have been offensive ... sorry :-)
EDIT2: Possible solution:
this.previousSibling.parentNode.removeChild(this.previousSibling);
because this.previousSibling might be the input element

Since you are building your HTML with the DOM, you don't have to set attributes for events:
replace remove.setAttribute("onclick"... by something like:
remove.onclick = function(ev){
feld.parentNode.removeChild(feld);
}
feld and the onclick function are defined in the same scope, you have a closure here. It makes feld available inside the function.

Related

javascript for all textarea

I want apply my JS on all my Textarea
$_PAGE->addJSOnLoad("
$('#textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
$('#compteur').text(msg);
'<span id=compteur>' 0 caractére(s)'</span>';
});
");
This code is in constructor of my class textarea I wnat call him 1 times for all textarea
You should change the jquery selector from $('#textarea') to $('textarea') so as to target all textarea in the document.
Also you may want to use $('.compteur') in place of $('#compteur') so that your can have multiple counters, one for each textarea. Do not forget to update your html correspondingly
Edit: Please use $(this).find('.compteur') in place of $('.compteur') so that only the counter within the current textarea is affected
$('#textarea')
selects a HTML element with the ID "textarea". So this will be at max one textarea-element. The selector for all textareas would be just
$('textarea')
javscript event handlers can take a parameter (Event), so
$('textarea').keyup(function() {
var nombreCaractere = $(this).val().length;
var msg = nombreCaractere + ' caractére(s)';
// code for display, todo!
}
would put the event handler on every textarea (<textarea>) on your page. However, the display for the character count is a bit more difficult, unless it's one fixed element that scrolls along.
but let's say, your textareas all have an attribute data-charcount="[id]" that has the id of a div or something, that will display the character count.
Then you could replace
// code for display, todo!
with
$("#"+this.dataset.charcount).text(msg); // <- assuming this works
and your example textarea should look like this:
<textarea data-charcount="compteur"></textarea>
<span id="compteur"></span>
please note: every id should only appear once!
edit replace event.target with this, and fixed small error with string concat

Change names of appended table row fields jQuery

I have a table in an html form containing a table that a row is added to every time a button is clicked. When each row is added, I want the name and id of each field in the new row (there are four) to be updated from "Id.0" in the first row to "Id.1" in the second row and then "Id.2" in the third, etc. I can accomplish this with the id no problem using
var next=$("#QualificationRequirements tr:last").clone();
fixIds(next,nexdex);
nexdex++;
$("#QualificationRequirements").append(next);
function fixIds(element, counter) {
$(element).find("[id]").add(element).each(function() {
this.id = this.id.replace(/\d+$/, "")+counter;
}
}
However I have found that the same logic does not apply to the name attribute, and
$(element).find("[name]").add(element).each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
causes an error that says I can't call "replace" on a null object, so it appears the name attribute is not being found.
Can anyone see what I'm doing wrong? Thanks!
The issue comes from this part of your statement: add(element)
See, element refers to the complete row, and rows don't have a name attribute. You just want to act upon the inputs inside the row that have the name attribute so you should remove that part from your code:
$(element).find("[name]").each(function() {
this.name = this.name.replace(/\d+$/, "")+counter;
});
There is no name property on an HTML element. Instead you'll need to access it as an attribute:
this.setAttribute('name', this.getAttribute('name').replace(/\d+$/, "")+counter);
Working Demo
use $(this).attr('name'); to get and set the name attribute.
The full line:
$(this).attr('name',$( this).attr('name').replace(/\d+$/, "")+counter);
Try this
$(element).find("[name]").add(element).each(function() {
this.attr("name",this.attr('name').replace(/\d+$/, "")+counter) ;
});

How to generate Divs containing tables with dynamically addable and removable rows? - JSfiddle Added

In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>

How insert an input field in a table cell?

Sorry for the noob question: I want to create a table with input fields where the can add new ones, if they are needed. But I can'T figure out how add another input field inside a cell where another input field already exists.
My code is:
var par=obj.parentNode;
while(par.nodeName.toLowerCase()!='tr')
{ par=par.parentNode; }
// this gives me the index of the row.. works fine.
cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
// this puts the content of the cells into the array "cell1"
var feld = cell1[1].createElement("input");
feld.setAttribute("name","avz_keywords" + avz_array + "[]");
feld.setAttribute("onblur","");
feld.setAttribute("type","text");
feld.setAttribute("size","30");
// Now I create a input element
// And now comes the problem:
cell1[1].appendChild(feld); // --> doesn't work
Has anyone a suggestion for me?
I got the idea to work without a table, theoratically that would work with my way. But that wouldn't be satisfying :/
If you look in a debugging console, you should see something like
TypeError: Object #<HTMLDivElement> has no method 'createElement'
Instead of creating the element from cell1[1], use document.createElement()
var feld = document.createElement("input");
You should use document.createElement("input"); instead of cell1[1].createElement("input");
As always (and as also stated in another answer here), the JavaScript console should be the first place to look for hints on what the problem is!
And wouldn't it actually be much easier if each table cell you want to add values to got a separate ID? Something containing perhaps the row index and the column index ... Then you could just select it directly.

Put focus on XUL textbox

I'm doing a Firefox extension. The extension has a sidebar. In this sidebar, I created some textboxes dynamically. How I can put the focus on the last textbox that I created?
This is the code, I want to put the focus in the textbox "userResponse" . The textbox is a XUL element.
var textResponse= document.createElement("textbox");
textResponse.setAttribute("id", "userResponse");
textResponse.setAttribute("class", "question");
textResponse.setAttribute("title", "Type your question here");
textResponse.onkeypress = numberOfResults;
textResponse.focus("");
var trResponse = document.createElement("tr");
var tdResponse = document.createElement("td");
tdResponse.appendChild(textResponse);
trResponse.appendChild(tdResponse);
tableQuestion.appendChild(trResponse);
I tried it with document.getElementById("userResponse").focus() but it doesn't work.
Calling textResponse.focus() is the correct way - but without parameters and after adding this element to the document. You can retrieve that element again of course by using document.getElementById() - but same thing there, you should do it after the element has been added to the document.

Categories

Resources