I'm trying to get a script to delete a table row.
var i = 1;
function addURL() {
var tr = document.createElement('tr');
tr.setAttribute("id", "url_row_" + ++i);
var td = tr.appendChild(document.createElement('td'));
td.style.valign = 'middle';
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url[]';
input.type = 'text';
input.size = '40'
var node = document.getElementById('myTable').tBodies[0];
node.insertBefore(tr, node.children[3]);
var link = document.createElement("a");
link.setAttribute("href", "");
link.setAttribute("style", "text-decoration: none;");
link.setAttribute("onClick", "removeURL('');return false;");
td = tr.appendChild(document.createElement('td'));
td=td.appendChild(link)
td.appendChild(document.createTextNode('-'));
}
function removeURL(divNum) {
var d = document.getElementById('myTable').tBodies[0];
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
This can produce as many url_row_(number) text fields as I want. I just don't know how to delete those rows.
I know doing
link.setAttribute("onClick", "removeURL('url_row_2');return false;");
will delete url_row_2, but what can I put at url_row_2 that will grab whatever id that the row is or what is the correct code to do this?
To do it that way, you would use string concatenation to concatenate i into the handler string to target the given tr.
link.setAttribute("onclick", "removeURL('url_row_" + i + "');return false;");
Don't use setAttribute for event listeners. Have a look at the Introduction to event handling at quirksmode.org, and especially on the simple event registration model. Also, you can just use the information from the event object to identify the row to remove:
function clickHandler(event) {
var anchor = this; // == event.targetElement
var tr = anchor.parentNode.parentNode;
tr.parentNode.removeChild(tr);
event.preventDefault(); // do not follow the href
}
function addURL() {
…
var link = document.createElement("a");
link.setAttribute("href", "#");
link.setAttribute("style", "text-decoration: none;");
link.onclick = clickHandler;
td = tr.appendChild(document.createElement('td'));
td.appendChild(link)
link.appendChild(document.createTextNode('-'));
}
Related
I want to make it so i append a link at the end of each row, but it says "Click Here", and then it openes a link? Ill show you my code below but i dont know really how to work this out, iv been thinking for 2 hours now and came up with nothing...
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellMovieName = row.insertCell(1);
var cellPrice = row.insertCell(2);
var cellLink = row.insertCell(3);
cellId.appendChild(document.createTextNode(childKey));
cellMovieName.appendChild(document.createTextNode(childData.Title));
cellPrice.appendChild(document.createTextNode(childData.Price));
cellLink.appendChild(document.createTextNode("CLICK ME" with the href attribute of childData.Title));
rowIndex = rowIndex + 1;
I think you need to do like this
You can't append child like that you need to do like
var list = document.getElementById("idhere");
var button = document.createElement('button');
button.value = "Click Me";
list.appendChild(button);
Now you can add attributes
var attribute = document.createAttribute("id"); // Can be class data-id whaterver you want onclick, anything you want
attribute.value = "time"; // can be anything
button.setAttributeNode(attribute);
// Some Examples
var span2 = document.createElement('span');
span2.innerText = snapshot.val().message;
var span_2_ID = document.createAttribute("id");
span_2_ID.value = "post";
// Time
var span3 = document.createElement('span');
span3.innerText = snapshot.val().time;
var span_3_ID = document.createAttribute("id");
span_3_ID.value = "time";
span1.setAttributeNode(span_1_ID);
span2.setAttributeNode(span_2_ID);
span3.setAttributeNode(span_3_ID);
var break1 = document.createElement('br');
var break2 = document.createElement('br');
I hope this helps you
Ok I figured it out... with a little bit of both of your guys's knowlage you have provided, i made a solution to this check below:
var text = document.createTextNode("This is link");
var link = document.createElement('a');
link.setAttribute('href', "https://google.com");
link.setAttribute('html', "test");
link.setAttribute('target', "_blank");
link.appendChild(text);
cellLink.appendChild(link);
rowIndex = rowIndex + 1;
So I Made The Text, Added It To The Column And Then Added The Attributes I Appreciate Everyone Helping Me!
I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}
I am trying to create a dynamic table with textboxes but I want the textboxes to be converted to upper case every time I write.
Any ideas on how to do this??
Currently this is how I am doing the dynamic table:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
//element.onkeyup = function(){alert()};
cell.appendChild(element);
}
n++;
}
I was trying to do a document.getElementById(element.id).value.toUpperCase() but I am getting an error with a null value for the element.id
Any help is greatly appreciated!
If you're ok with a non JavaScript solution, you could apply this CSS to your inputs:
text-transform: uppercase;
That would make the text uppercase from the beginning...
Darkajax's solution, works, you can target it to inputs within a table with a specific ID
with
#tableid input
{
text-transform: uppercase;
}
I tested your code with the onkeyup function activated:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
cell.appendChild(element);
}
n++;
}
And that worked. However, it uses the last element.id computed for every call to the function... so, when I created one row of 3 cells, every time I typed into a cell, it would alert "102" regardless of which cell I typed in.
This is because the onkeyup function is dynamic. It is called on the keyup action - not set when the object is created. So it uses the element.id value that exists at the time of the action, not what it was when you passed it in the first time. I hope that makes sense.
I had this issue myself on a recent project. One solution is to create a separate function for the inner workings of the for loop as such:
var n = 1;
function createRow (n, i) {
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
return element;
}
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
element = createRow(n, i);
cell.appendChild(element);
}
n++;
}
This code alerts the correct element.id value.
EDIT: you can change the onkeyup() line to read:
element.onkeyup = function(){document.getElementById(element.id).value = document.getElementById(element.id).value.toUpperCase();};
And it should work as you want it to.
with jQuery it will be like
$('.yourClass').val($(this).val().toUpperCase());
or
$('#yourId').css({'text-transform' : 'uppercase'})
In javascript, how can we detect which row of the table is clicked? At present what i am doing is, i am binding the the method at run time like this.
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
[ copied from [ http://webdesign.maratz.com/lab/row_index/ ] ]
But i don't like this approach. Is there any alternative? My problem is just to get the index of the row which is clicked.
No jQuery please :D.
You can use event delegation for that. Basically you add one clickhandler to your table. This handler reads out the tagname of the clicked element and moves up the DOM tree until the containing row is found. If a row is found, it acts on it and returns. Something like (not tested yet, but may give you ideas):
var table = document.getElementById('my_table');
table.onclick = function(e) {
e = e || event;
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode,
isRow = function(el) {
return el.tagName.match(/tr/i));
};
//move up the DOM until tr is reached
while (parent = parent.parentNode) {
if (isRow(parent)) {
//row found, do something with it and return, e.g.
alert(parent.rowIndex + 1);
return true;
}
}
return false;
};
The this keyword can be used to get the parentNode of the cell, which is a <tr> element. The <tr> element has a property for the row number, .rowIndex.
The Event:
onclick='fncEditCell(this)'
The Function:
window.fncEditCell = function(argThis) {
alert('Row number of Row Clicked: ' + argThis.parentNode.rowIndex);
};
Full Working Example Here:
jsFiddle
Dynamically Set OnClick Event
Use .setAttribute to inject a click event:
cell2.setAttribute("onmouseup", 'editLst(this)');
Example of Dynamically Creating a Table:
for(var prprtyName in rtrnTheData) {
var subArray = JSON.parse(rtrnTheData[prprtyName]);
window.row = tblList.insertRow(-1);
window.cell1 = row.insertCell(0);
window.cell2 = row.insertCell(1);
window.cell3 = row.insertCell(2);
window.cell4 = row.insertCell(3);
window.cell5 = row.insertCell(4);
window.cell6 = row.insertCell(5);
window.cell7 = row.insertCell(6);
window.cell8 = row.insertCell(7);
window.cell9 = row.insertCell(8);
cell1.setAttribute("onmouseup", 'dletListing(this.title)');
cell1.setAttribute("title", "'" + subArray.aa + "'");
cell2.setAttribute("onmouseup", 'editLst(this)');
cell2.setAttribute("title", "'" + subArray.aa + "'");
cell1.innerHTML = "Dlet";
cell2.innerHTML = "Edit";
cell3.innerHTML = subArray.ab;
cell4.innerHTML = "$" + subArray.ac;
cell5.innerHTML = subArray.ad;
cell6.innerHTML = subArray.ae;
cell7.innerHTML = subArray.af;
cell8.innerHTML = subArray.ag;
cell9.innerHTML = subArray.meet;
};
This uses sectionRowIndex to get the index in the containing tBody.
function getRowIndex(e){
e= window.event || e;
var sib, who= e.target || e.srcElement;
while(who && who.nodeName!= 'TR') who= who.parentNode;
if(who){
alert(who.sectionRowIndex+1)
if(e.stopPropagation) e.stopPropagation();
else e.cancelBubble= true;
// do something with who...
}
}
onload= function(){
document.getElementById('my_table').onclick= getRowIndex;
}
I tried Alan Wells written answer, but it was returning, undefined.
So, I modified a little, to get the row index as follows:
argThis.rowIndex
This will return the row index for the row clicked.
modify the <tr> tag:
<tr onclick="fncEditCell(this)" >
Then, add a script tag at the bottom of the HTML:
<script>
window.fncEditCell = function(argThis) {
alert('Row number of Row Clicked: ' + argThis.rowIndex);
};
</script>
As an example, you can see this image:
I created a form dynamically when onclick a button "Add Record" in a form. The new form is created and assigned to a div, after rendering this form I can't get any of the values in textboxes.
while testing I tried many ways to get the form and elements and it returns undefined. The name of the form is "addrec_form".
I tried
var address1 = document.forms.addrec_form.address.value
var address1 = document.forms['addrec_form'].elements['address']
assigned it to a variable and then use alert("value of address is: " + address1)
all this returns document.forms.addrec_from is undefined. While testing with firebug I set up the button onclick of this new form to just show an alert with just a string for testing purposes, but when debugging although the button onclick is not click is still in the process of rendering it displays the alert message then finishes and all looks okay but can't access the values in the form.
Can some one explain to me how can I get this working? I might have code something wrong, but I did consult my books and samples I can't seem to figure out.
This is my code:
function addRec(){
var browserName = whichBrs();
//var outterDiv =
document.getElementById("gridDiv").style.visibility="visible";
if(document.getElementById("AddRecords").style.visibility == "hidden")
{
document.getElementById("AddRecords").style.visibility = "visible"
}
var tbl = document.createElement("table");
tblbody = document.createElement("tbody");
// applies the css to the element i.e. element is tbl class is list2
browserDetect(tbl, "list2");
var tr1 = document.createElement("tr");
tr1.style.background = "#e8edff";
var th1 = document.createElement("th");
browserDetect(th1, "cancelimgX");
tr1.appendChild(th1);
var img1 = document.createElement("img");
img1.setAttribute("src", "images/close.png");
img1.onclick = function(){setDivVisibility(); return false;};
img1.setAttribute("title", "Close Window");
img1.style.cursor="pointer";
img1.style.height="16px";
img1.style.border="0px"
th1.appendChild(img1);
var tr2 = document.createElement("tr");
tr2.style.background = "#e8edff";
var td1 = document.createElement("td");
td1.style.padding = "0.5em 0.5em 0.5em 0.5em";
var fieldset1 = document.createElement("fieldset");
fieldset1.style.padding = "0 0 0.5em 0";
fieldset1.style.border = "1px solid #001685";
fieldset1.style.background = "#e8edff";
var legend1 = document.createElement("legend");
legend1.background = "#e8edff";
var legendtxt = document.createTextNode("Adding a Record");
var fontA = document.createElement("font");
fontA.style.color = "#001685";
fontA.style.fontWeight = "bolder";
fontA.appendChild(legendtxt);
legend1.appendChild(fontA);
var form1 = document.createElement("form");
form1.setAttribute("method", "post");
form1.setAttribute("name", "addrec_form");
form1.setAttribute("id", "addrec_form");
var tbl2 = document.createElement("table");
var tbl2body = document.createElement("tbody");
browserDetect(tbl2, "tblAddRec");
var address1 = "Address";
var city1 = "City";
var hardware_number1 = "Hardware Number";
var hardware_status1 = "Hardware Status";
var software_status1 = "software Status";
var premise1 = "Premise";
var service_point1 = "Service Point";
var val = "Create Record";
// creating labels and textboxes
genLblBxs(address1,tbl2body, "address");
genLblBxs(city1,tbl2body, "city");
genLblBxs(hardware_number1,tbl2body, "hardware_number1");
genLblBxs(hardware_status1,tbl2body, "hardware_status1");
genLblBxs(software_status1,tbl2body, "software_status1");
genLblBxs(premise1,tbl2body, "premise");
genLblBxs(service_point1,tbl2body, "service_point");
genFooter(val, tbl2body);
tbl2.appendChild(tbl2body);
form1.appendChild(tbl2);
fieldset1.appendChild(legend1);
fieldset1.appendChild(form1);
td1.appendChild(fieldset1);
tr2.appendChild(td1);
tblbody.appendChild(tr1);
tblbody.appendChild(tr2);
tbl.appendChild(tblbody);
var addrecorddiv = document.getElementById("AddRecords");
addrecorddiv.appendChild(tbl);
}
function genFooter(val, tbl2body)
{
var tr = document.createElement("tr");
var td = document.createElement("td");
td.colSpan = "2";
td.align="right";
td.vAlign="bottom";
td.height = "35px";
var btnCreateRec = document.createElement("INPUT");
btnCreateRec.type="button";
btnCreateRec.id = "btnRec";
btnCreateRec.name = "btnRec";
btnCreateRec.value = val;
btnCreateRec.style.color = "#FFFFFF";
btnCreateRec.style.border = "1px solid";
btnCreateRec.style.backgroundColor = "#416ADC";
btnCreateRec.height = "20";
btnCreateRec.onmouseover = function(){ document.getElementById("btnRec").style.backgroundColor = "#001685"; return false;};
btnCreateRec.onmouseout = function(){ document.getElementById("btnRec").style.backgroundColor = "#416ADC"; return false;};
// THIS IS WHERE PASSING THE ARRAY OF TEXTBOXES IS PASSED TO A FUNCTION FOR FURTHER PROCESSING
// THIS IS WHAT I CAN'T FIGURE OUT
btnCreateRec.onmouseclick = function(){insertRequest(document.forms.addrec_form, 'INSERT_ROW');};
td.appendChild(btnCreateRec);
tr.appendChild(td);
tbl2body.appendChild(tr);
}
function genLblBxs(value_id, tbl2body, box_id)
{
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.setAttribute('noWrap','true');
td1.align="left";
td1.width="15%";
td1.vAlign="baseline";
td1.style.padding = "0.5em 0 0 0.5em";
var lbl = document.createTextNode(value_id);
var font1 = document.createElement("font");
font1.style.color = "navy";
font1.appendChild(lbl);
value_id = value_id.toLowerCase(); ;
var td2 = document.createElement("td");
td2.align = "left";
td2.style.padding = "0 0.5em 0 0.5em";
var txtBox = document.createElement("INPUT");
txtBox.type="text";
txtBox.id =box_id;
txtBox.name = box_id;
txtBox.size = "37";
txtBox.color = "navy";
txtBox.style.border = "1px solid #C3D5FF";
td1.appendChild(font1);
td2.appendChild(txtBox);
tr.appendChild(td1);
tr.appendChild(td2);
tbl2body.appendChild(tr);
}
Try stripping down your code first to just include the dynamic adding of the form and getting the values in the textbox to make your code easier for everybody else to understand and it will also make it easier for you to debug your code. Don't forget to backup the original code.
I tried copying and pasting your code onto an empty page with a container div defined. It failed on a couple of missing functions (whichBrs and browserDetect), which I presume you have defined elsewhere. Then, there's no such thing as onmouseclick, which I replaced with onclick. After that it worked ok in IE8 and FF3: alert(document.forms.addrec_form.address.value) within insertRequest showed me whatever I typed into the address field.
Did you try using firebug(in FF) to determine if there are javascript errors on your page?
Try debugging and looking at the DOM tree in its views.
I apologize for providing so much code, this is my first time
requesting for assistance, I'll be more diligent next time.
Thanks to all for your suggestions.
Originally the addRec() was called by onclick on a button in a form/table,
then this form/table was rendered and the onclick was not working to pass
the textboxes values.
I managed to get it working as follows:
Created a function to call addRec(), after that I added
document.getElementById("btnRec").onclick = function(){insertRequest(document.forms.addrec_form, 'INSERT_ROW');};
Thanks again...