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...
Related
I'm working on a table content with JS. What I can update with a button or clear data from the table.
Phone Number: phoneNumber.value
Bay Number: bayNumber.Value (it's not added yet, but will work same)
The First column in the table is always the same (Phone Number and Bay Number), but the second column should change what is in the input after I press the save button (it works fine) Just if I press the delete, it deletes the all table.
I think the problem is how I created the table, but don't know how should I fix it.
//FORM//
var form = document.createElement('div');
form.style.width = "500px";
form.style.height = "500px";
form.style.margin = "auto";
form.style.textAlign = "center";
form.style.paddingTop = "20px";
form.style.background = "grey";
form.classList.add("printVisible");
document.body.appendChild(form);
var phoneNumber = document.createElement("INPUT");
phoneNumber.setAttribute("type", "text");
phoneNumber.value = "07";
phoneNumber.classList.add("hiddenPrint");
form.appendChild(phoneNumber);
var bayNumber = document.createElement("INPUT");
bayNumber.setAttribute("type", "text");
bayNumber.value = "Bay Number";
bayNumber.classList.add("hiddenPrint");
form.appendChild(bayNumber);
var buttonSave = document.createElement("BUTTON");
buttonSave.addEventListener("click", saveDatas);
var buttonSaveT = document.createTextNode("Save");
buttonSave.appendChild(buttonSaveT);
form.appendChild(buttonSave);
var buttonClear = document.createElement("BUTTON");
buttonClear.addEventListener("click", clearDatas);
var buttonClearT = document.createTextNode("Clear");
buttonClear.appendChild(buttonClearT);
form.appendChild(buttonClear);
var phoneNumberT = document.createElement("P");
form.appendChild(phoneNumberT);
var bayNumberT = document.createElement("P");
form.appendChild(bayNumberT);
//SAVE BUTTON//
function saveDatas() {
tablePhoneNumberTx.textContent = phoneNumber.value;
bayNumberT.textContent = bayNumber.value;
}
//CLEAR BUTTON//
function clearDatas() {
tablePhoneNumberTx.textContent = "";
bayNumberT.textContent = "";
}
//TABLE//
let body = document.body;
let tbl = document.createElement("table");
tbl.style.textAlign = "center";
tbl.style.margin = "auto";
let tablePhoneNumberTx = tbl.insertRow();
let tablePhoneNumber = tablePhoneNumberTx.insertCell();
tablePhoneNumber.appendChild(document.createTextNode(`Phone Number`));
tablePhoneNumberTx.appendChild(document.createTextNode(phoneNumber.value));
tablePhoneNumber.style.border = "1px solid black";
tablePhoneNumber.style.width = "250px";
tablePhoneNumberTx.style.border = "1px solid black";
tablePhoneNumberTx.style.background = "250px";
form.appendChild(tbl);
P.S. Its a TamperMonkey Script so, must be everything in JS
some sort of code factorization you could use, but since you wrote "only JS" I wonder why you are referencing CSS classes?
const newEl = ( tag, styling={}, attrbs={} ) =>
{
let elm = document.createElement(tag)
for(let key in styling) elm.style[key] = styling[key]
for(let key in attrbs) elm[key] = attrbs[key]
return elm
};
let myDiv = document.body
.appendChild
( newEl('div'
, {width:'200px', margin:'auto'}
, {className:'toto', textContent:'hello world'}
) );
console.log( myDiv )
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 looking to have it so when the user clicks on one of the "Get Sequence" buttons, it calls a function, which is shared among all "Get Sequence" buttons, that passes in the values specific to that row and col.
For example, if the user were to click on the rad51/mouse "Get Sequence" button, the function would pass in "rad51" and "mouse". HTML
What I have thus far:
function createTable(){
//call firebase
var genes = ["rad51", "dmc1"];
var genomes = ["human", "mouse", "dog"];
var geneCount = genes.length;
var genomeCount = genomes.length;
var table = document.getElementById("inventory");
var firstRow = document.getElementById("firstRow");
var x = 0;
var y = 0;
while(x < geneCount){
var data = document.createElement('td');
var text = document.createTextNode(genes[x]);
data.appendChild(text);
firstRow.appendChild(data);
x++;
}
while(y < genomeCount){
//create new row
var newRow = document.createElement('tr');
var data = document.createElement('td');
var text = document.createTextNode(genomes[y]);
data.appendChild(text);
newRow.appendChild(data);
x = 0;
while(x < genes.length){
var currentGene = genes[x];
var currentGenome = genomes[y];
data = document.createElement('td');
data.setAttribute("id", currentGene);
var getSequenceButton = document.createElement("button");
text = document.createTextNode("Get Sequence");
getSequenceButton.appendChild(text);
???----> getSequenceButton.addEventListener("click", getId(this.parent));
var changeColorButton = document.createElement("button");
data.appendChild(getSequenceButton);
data.appendChild(changeColorButton);
newRow.appendChild(data);
x++;
}
table.appendChild(newRow);
y++;
}
};
I fixed my own problem. So what I did was assign an id to each of the buttons to the information that I was interested in. The function assigned to each button passed in the event object where I could then parse for the id with event.target.id
I think this could be a possible solution using Jquery, assuming your table doesn't change its structure:
$(document).ready(function(){
$(".table_button").click(function(){
//alert(this.innerHTML);
var rowValue = $(this).parent().children().first().text();
var columnValue = $("th").eq($(this).parent().find(this).index()).text();
//alert($(this).parent().find(this).index());
alert("RowValue: " + rowValue + "\n" + "ColumnValue: " + columnValue);
});
});
https://jsfiddle.net/ow1naqvL/
Basically i get the first <td> of the relative <tr> of the button row (to get "human" and so on). Then, i use the button index for get the text of <th> at that index.
Pure Javascript solution could be a little bit tricky.
Hope it helps
Please I tried getting the values imputed by the user but when I input the value and cluck submit, the page reloads without showing the values. any help please. Thank you
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '2px solid yellow';
var n = 10
for (var i = 0; i < n; i++) {
var tr = tbl.insertRow();
var td = tr.insertCell(0);
var tf = tr.insertCell(0);
var input = document.getElement('input');
input.name = "input2";
input.id = "input2";
input.value = "";
var clone = input.cloneNode();
clone.name = "input1";
clone.id = "input1";
td.appendChild(clone);
tf.appendChild(input);
td.style.border = '2px solid yellow';
tf.style.border = '2px solidyellow';
}
var form = document.createElement("form");
form.appendChild(tbl);
body.appendChild(form);
var submit = document.createElement("input");
submit.type = "submit";
Submit.on click = 'show()'
function show() {
var c = document.getElementById("input2").value;
document.write(c.value);
}
form.appendChild(submit)
tableCreate();
var c = document.getElementById("input2");
document.write(c);
I don't think doing things like myElement.onclick='show()' makes sense, since you are doing things in JS anyway. Why not just add an event listener to the form, which would listen for submit? Preventing the default action (which includes refreshing the page) should be what you are looking for, if I got you correctly.
form.addEventListener('submit', function(event){
event.preventDefault(); // <-- prevents page reload
//
// Here goes your code, that should
// execute when the form is submitted
});
EDIT:
Here's a JSFiddle. Enter some values, press submit and then check your console. You will see 2 arrays - one with the left values, one with the right ones.
I am dynamically generating an HTML table of variable length with javascript, and inside that form I am inserting a button for each row. The button should call a function when it is clicked, but right now the function is called for each row upon page load/table generation. If there are multiple buttons (since I create one for each row), each button calls the function. I know this because I have an alert with the name of the caller in upVoteA().
Here is the portion of the call that creates the button (entire function is at the bottom of this post):
var tr1 = document.createElement('TR');
var upvote = document.createElement('button')
upvote.name = i + offset
upvote.onclick = upVoteA(upvote.name)
upvote.innerHTML = "Upvote link"
tr1.appendChild(upvote)
Am I missing some property to change this behavior? What is wrong with my code?
Also, here is the full function I call to generate the table in case that is helpful..
function answerTableText(idd, offset)
{
var answerDiv = document.getElementById("answerShow")
while(answerDiv.firstChild){
answerDiv.removeChild(answerDiv.firstChild)
}
if(qnumans_array[idd] >0)
{
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<qnumans_array[idd]; i++){
var tr = document.createElement('TR');
var td1 = document.createElement('TD')
td1.innerHTML = answer_array[i + offset]
var td2 = document.createElement('TD')
var tr1 = document.createElement('TR');
//tr1.innerHTML = "Upvote"
var upvote = document.createElement('button')
upvote.name = i + offset
upvote.onclick = upVoteA(upvote.name)
upvote.innerHTML = "Upvote link"
tr1.appendChild(upvote)
var tr2 = document.createElement('TR');
tr2.innerHTML = "Downvote"
td2.appendChild(tr1)
td2.appendChild(tr2)
td1.padding = "1em"
td2.padding = "1em"
tr.appendChild(td1)
tr.appendChild(td2)
tr.style.borderBottom = "thin solid #37434E"
tr.style.borderTop = "thin solid #37434E"
tableBody.appendChild(tr);
}
answerDiv.appendChild(table);
}
else answerDiv.innerHTML = "No answers yet."
}
This line:
upvote.onclick = upVoteA(upvote.name)
calls upVoteA and assigns its return value to the onclick property, exactly the way
a = foo()
calls foo and assigns its return value to a.
Instead, assign a function to it, either using an explicit wrapper:
upvote.onclick = function() {
upVoteA(upvote.name);
};
...or using Function#bind:
upvote.onclick = upVoteA.bind(null, upvote.name);
When you say:
upvote.onclick = upVoteA(upvote.name)
You are immediately calling that function, and assigning its result to onclick. You want something like:
upvote.onclick = function() {
upVoteA(upvote.name);
};