how to avoid printing html code inside textbox as value - javascript

I am creating a dynamic table and getting td values from array, my goal was when I click on any cell that convert to input box and get this td value as input value so we can change and when I click on another td the previous td turn back to it's original position with new or same old value, Now this is almost happening, problem is when I click on td it turn to input box and when I click again on the same input box it prints it's html code inside the text box as it's value and then the all td's go crazy, like this: it creates two input boxes in same time and sometime prints the html code inside td without creating input box. I am new to these things trying to learn and stuck on this for two days please help me to come out. Thanks in advance
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 1;
var getInputLength = getInput.length+1;
for(var j=0; j<allTds.length;j++){
allTds[j].onclick = function(){
thisInHtml = this.innerHTML;
var thisId = this.id;
if(inputs.length != 0){
inputsParent.removeChild(inputs);
inputsParent.innerHTML = getInputVal;
flag = 1;
}
this.innerHTML = thisInHtml;
if(getInputVal != ""){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
getInput = document.getElementsByTagName("input");
getInputVal = document.getElementById("thisInputId").value;
}
if(getInputLength > 0){
for(var k =0; k<getInputLength;k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
}
}
}
}
}

Related

How do I get the row and column values when a button is pressed in a HTML table?

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

Extracting values from a table in Javascript

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.

Dynamically creating multiple textboxes depending on minimum number of characters in previous textbox/ javascript/asp

Hi I have a webform in which i need to add multiple textboxes dynamically depending on the entry in previous textbox.. Even if one character is entered in the previous textbox it should generate new texbox beside it without losing the focus from previous textbox and it should allow me to enter as many characters without limiting..
Here is my code :
getId = function ()
{
var id = 1;
return function ()
{
id++;
}
}
function CreateTextbox()
{
var box = document.getElementById("divCreateTextbox");
var curr = 'txt' + getId();
var inp = document.createElement('input');
inp.type = 'text';
inp.name = 'textfield';
inp.setAttribute("id", curr);
inp.setAttribute("minlength",'1');
box.appendChild(inp);
inp.setAttribute('onkeyup', 'moveOnMin(this)');
inp.focus();
}
function moveOnMin(s)
{
if(s.value.length >= parseInt(s.getAttribute("minlength")))
{
CreateTextbox();
}
The problem with the above code is, it is just allowing me to enter 1 character in one textbox and shifts the focus on new textbox. Everytime I try to enter more than one character in the textbox it creates new textboxes for each character. Any solutions ??
Try this.
function CreateTextbox()
{
var box = document.getElementById("divCreateTextbox");
var curr = 'txt' + getId();
var inp = document.createElement('input');
inp.type = 'text';
inp.name = 'textfield';
inp.setAttribute("id", curr);
inp.setAttribute("minlength",'1');
box.appendChild(inp);
inp.setAttribute('onkeyup', 'moveOnMin(this)');
inp.setAttribute("textBoxAdded", "0");
//inp.focus();
}
function moveOnMin(s)
{
if (s.value.length == parseInt(s.getAttribute("minlength")) && s.getAttribute("textBoxAdded") == "0")
{
CreateTextbox();
s.setAttribute("textBoxAdded", "1");
s.focus();
}
}
I have changed your code to:
1. remain focus on existing TextBox; and
2. let the TextBox added only once from every TextBox

Cannot manage to use innerHTML

I'm new to Stack Overflow and also in JavaScript. So, first of all, hello to everyone and thanks in advance for your help.
I'm using Incomedia Website X5 Evolution to create a website. On one of the page, I want to populate a table with data from a server. So, I've created a table and insert in each cell this HTML code:
<!--#0000,0000-->
Values are representing the row and the column. I managed to write a javascript to change the value of each cell. But when I want to replace the content of the HTML pahe using innerHTML, it does not work. Nevertheless, everything seems correct as the old and the new html content is the same. Even if I just use again the original variable, it still doesn't work.
Could you tell me where is the problem please ?
Here the javascript code:
<script>
var i;
var div = document.getElementById('imTableObject_1');
div = document.getElementsByTagName('table');
var htmlContent = div[0].innerHTML;
var newHtmlContent = div[0].innerHTML;
var test = div[0].innerHTML;
var row,col;
//I can't understand why the scrip stop running at this line. I didn't change anything...
div[0].innerHTML = newHtmlContent ;
for (i=htmlContent.length - 5; i > -1; i--) {
if(htmlContent.charAt(i)=='#') {
//alert(i);
//alert(htmlContent.substring(i+6,i+10));
row = parseInt(htmlContent.substring(i+1,i+5));
col = parseInt(htmlContent.substring(i+6,i+10));
newHtmlContent = insertText(row,col,newHtmlContent,i);
};
};
alert(div[0].innerHTML);
alert(newHtmlContent );
//This does not work
div[0].innerHTML = newHtmlContent ;
alert("Done !");
function insertText (row, col, text, index) {
var length;
var newText;
length = getTextLength (text,index + 13);
//alert(htmlContent.substring(index+13,index+13+length));
newText = text.substring(0,index+13);
newText += "Titi too !";
newText += text.substring(index+13+length,text.length);
//alert(newText);
return newText ;
}
function getTextLength (text,startIndex) {
var i = 0;
for(i = startIndex ; i < text.length ; i++) {
//alert(text.substring(i,i+7));
if(text.substring(i,i+7) == "</span>") {
return i - startIndex ;
};
};
return -1;
}
</script>
You set:
var newHtmlContent = div[0].innerHTML;
And then:
div[0].innerHTML = newHtmlContent ;
You're setting its content to what its content already was. Hence, no change occurs.
Change the 3rd row to
div = document.getElementsByTagName('td');
to look for <td> tags instead of <table> tags. <table>s can't directly store text data so I guess their innerHTML doesn't work as expected either.
I managed to get it working here: http://jsfiddle.net/mgabor/ZMaW6/1/

Obtain values from a form text field

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...

Categories