How can I remove unwanted piece of HTML markup on the page? - javascript

I have trouble with this piece of code. When I click it once, all is good and the behavior is as designed , but when I click it more than once, then there is all bunch of HTML that appears in the div (text area). How should I revise my JS to make it not happen?
HTML :
<div id="transcriptText">Lorem ipsum dolor sit amet </div>
<br>
<div id="divideTranscript" class="button"> Transform the Transcript! </div>
JS :
window.onload = function() {
var transcriptText = document.getElementById("transcriptText");
var newTranscript = document.createElement("div");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = EventHandler;
function EventHandler() {
changeText();
}
function changeText() {
var sArr = transcriptText.innerHTML.split(" ");
transcriptText.innerHTML = "";
console.log(sArr);
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}
};
Here is it live http://jsfiddle.net/b94DG/1/

The main problem is that you use the innerHTML property instead of the .textContent property each time.
Here is an improved version of changeText() that doesn't matter how many times you run it:
function changeText() {
var sArr = transcriptText.textContent.split(/\s+/g); // changed
transcriptText.innerHTML = "";
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
if (!item) continue; // changed: don't add spans for empty strings
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}

Related

How to remove an item in an array using an onclick function?

In this code, I am trying to push items into the array and then removing them.
If you see below, the create button will give me a blank input and a button that stores it into an array. After it is pushed into the array, the view button goes through the array and displays all the items with the buttons "edit" and "delete" beside it. This is where my problem lies... for each item that is put into the array, it displays it on the Html and has its own buttons. How do I delete that item from the array when I click on a specific delete button?
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var arr1 = [];
//create button
create.onclick = function () {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function () {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function () {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
display.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
}
//del button
del.onclick = function () {
}
}
}
You need some way of identifying the element you want to delete so it can be tied to the delete function. Here's some code that shows one possible way using data attributes.
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var results = document.getElementById("results");
var arr1 = [];
//create button
create.onclick = function() {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function() {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function() {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
results.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
del.setAttribute('data-item-index', i);
//set onclick fn for del button
del.onclick = function() {
var itemIndex = this.getAttribute('data-item-index');
arr1.splice(itemIndex, 1);
console.log(arr1);
results.innerHTML = '';
view.click();
};
}
}
<div id='display'>
<button id="create">Create</button>
<div>
<input type="text" id='text'>
<button id='push'>Push</button>
</div>
<button id='view'>View</button>
<div id='results'></div>
</div>

by clicking on input box twice it's printing it's own html code inside input box

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: <input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'> 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.
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];
}
}
}
}
}
http://jsfiddle.net/mohsinali/npckf9xs/6/
After some struggle I came up with the solution on my own and I fix the issue, I also figure it out that it's always simple we just have to think right. It can be more optimize I believe.
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 0; var thisInputVal = ""; var thisTdId = "";
var cellIndex = ""; var thisRowIndex = "";
for(var j=0; j<allTds.length;j++){
allTds[j].ondblclick = function(){
thisInHtml = this.innerHTML;
getInput = document.getElementsByTagName("input");
if(getInput.length === 0){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
thisTdId = this.id;
cellIndex = this.cellIndex;
var rows = document.getElementsByTagName('tr');
for(var o=0; o<rows.length;o++){
rows[o].ondblclick = function(){
thisRowIndex = this.rowIndex-1;
}
}
}
else if(getInput.length > 0){
for(var k=0; k<getInput.length; k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
thisInputVal = inputs.value;
inputsParent.removeChild(inputs);
flag = 1;
}
}
if(flag === 1){
var getTdById = document.getElementById(thisTdId);
getTdById.innerHTML = thisInputVal;
if(cellIndex === 0){
proArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 1){
proColorArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 2){
proPriceArr[thisRowIndex] = thisInputVal;
}
flag = 0;
}
}
}
}

Converting if...else statement into for-loop

I have one generous piece of code with several if...else statements and I would need to convert this into a loop. The problem is, each time it makes a loop, there must be some different id to the function so it works properly.
Let's take a look at the code:
// Count how many inputs there are in element with id "tempResult"
var inputCount = document.getElementById('tempResult').getElementsByTagName('input').length;
if (inputCount == 1) // if there is 1 input, generate 1 line
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
}
else if (inputCount == 2) // if there are 2 inputs, generate 2 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
}
else if (inputCount == 3) // if there are 3 inputs, generate 3 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
}
else if (inputCount == 4) // if there are 4 inputs, generate 4 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
var str = document.getElementById('tempString4').value;
var arrayOfStrings4 = str.split('*');
for(var i = 0; i < arrayOfStrings4.length; i++)
{
var div4 = document.getElementById('div4');
var mi4 = document.createElement('input');
mi4.setAttribute('type', 'text');
mi4.setAttribute('size', '5');
mi4.setAttribute('id', 'string4' + (i+1));
mi4.setAttribute('value', arrayOfStrings4[i]);
div4.appendChild(mi4);
}
}
As you can see, we repeat a certain amount of time the same function depending on how much inputs we have in the div tempResult:
var str = document.getElementById('tempStringX').value;
var arrayOfStringsX = str.split('*');
for(var i = 0; i < arrayOfStringsX.length; i++)
{
var divX = document.getElementById('divX');
var miX = document.createElement('input');
miX.setAttribute('type', 'text');
miX.setAttribute('size', '5');
miX.setAttribute('id', 'stringX' + (i+1));
miX.setAttribute('value', arrayOfStringsX[i]);
divX.appendChild(miX);
}
The X, replaced by numbers each time, are important, the function will not properly work without it (except for the divX, I could generate the inputs inside the same div, but whatever). The above code is working perfectly.
What I'm trying to do, is to use a for() instead of if...else(), so that I don't need to manually edit the code each time we add a new div. I'm not very familiar with for() and my tries with the already existing ones in my code as models were not successful.
Here's how the HTML looks like:
<div id="tempResult">
<input type="text" id="tempString1" value="valueTempString1" />
<input type="text" id="tempString2" value="valueTempString2" />
<input type="text" id="tempString3" value="valueTempString3" />
<input type="text" id="tempString4" value="valueTempString4" />
</div>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
And if you wonder what this whole code is doing, explanation's here. Thanks :)
The if loops in the code you posted would be used as a for loop. i.e, you would be iterating the same times the input count would be. So you can condense the same code into this.
var inputCount = document.getElementById('tempResult')
.getElementsByTagName('input').length;
// First loop that iterates over the input count
for (var j = 1; j <= inputCount; j++) {
var str = document.getElementById('tempString' + j).value,
arrayOfStrings = str.split('*');
// Second loop would iterate over the strings that would be split
for (var i = 0; i < arrayOfStrings.length; i++) {
var div = document.getElementById('div' + j);
var mi = document.createElement('input');
mi.setAttribute('type', 'text');
mi.setAttribute('size', '5');
mi.setAttribute('id', 'string' + j + '-' + (i + 1));
mi.setAttribute('value', arrayOfStrings[i]);
div.appendChild(mi);
}
}
Why do you want the variable to have the number of the item? You could run all code inside the for statement and the variable name doesn't have to change.
thisdiv = document.getElementById('div'+i);
thisdiv....all changes to thisdiv go here

createElement (input) with Id ;with counter ,Id1,Id2,Id3

i trie to generate dynamic Input fields with unique Ids but i stucked:
function addTxtBx(){
var txtBxHolder = document.getElementById('txtBoxHolder');
var newTxtBx = document.createElement('input');
newTxtBx.type = 'text';
var i=1;
//newTxtBx.id = document.getElementById("txtWaypoint"[i])
if(i<10){
newTxtBx.id = "txtWaypoint"+[i];
i++;
break;
}
txtBoxHolder.appendChild(newTxtBx);
}
i tried it with a for() but always got Id='name'9,
i know im an trainee. :)
I think so where you miss to loop it properly.
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input');
text.type = "text";
text.id = "txtWaypoint" + i; //id created dynamically
document.getElementById('divsection').appendChild(text);
}
}
Try it

Adding select boxes dynamically

I have made a simple dynamic form to generate input boxes.
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+"/>
<input type="button" onclick="removeSelect();" value="-"/>
<input type="button" onclick="xmlData();" value="XML" />
</div>
<div id="main">
</div>
</body>
Here's the javascript code:
(function () {
var selele=0;
var brindex=0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
var textbox = document.createElement('input');
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
});
I can't get it to work on jsFiddle, the buttons don't work.
They work fine if I embed it in a tag.
Can anybody help me fix them.
EDIT: I guess i added anonymously because I wanted the var selele and brindex globally for all these functions.
I have made the code changes.
JSFIDDLE
Your functions are within an anonymous function and thus not available from outside.
First remove the code from the anonymous function (see here: http://jsfiddle.net/uH84W/6/), then fix the console errors you get (I assume that's not the whole code).
function addSelectBox() {...
In your fiddle you select onload but you change onload to no warp-in or no warp-in now it's work fine

Categories

Resources