Generate and Render html from a set of inputs - javascript

I have a word matching exercise that takes a set of inputs.
The program reads the html from the input boxes.
Then the html is displayed in a textarea element.
When the user clicks "render html" the key words and descriptions are displayed. The html displayed by the program are the values are taken from value of the textarea element.
The input elements for the html are
<div id="inputBoxes" class="inputBoxes">
<title>Input:</title>
<div class="row">
Title: <input id= "title_input" type="text">
</div>
<div class="row">
Key Term 1: <input id="el1" type="text" value="">
</div>
<div class="row">
Description 1: <input id="dl1" type="text" value="">
</div>
<div class="row">
Key Term 2: <input id="el2" type="text" value="">
</div>
<div class="row">
Description 2: <input id="dl2" type="text" value="">
</div>
</div>
I have 3 global variables to keep track of the numberOfInputs, htmlGenerated, htmlRendered. The reasoning behind this is to check if
New inputs have been added. If new inputs have been added then when the user clicks generate html those new inputs should be added. When the user clicks render html those new inputs should be added.
Check if html has been generated. If the html was generated then it should be removed before generating new html.
Check if html has been rendered. If the html was rendered then it should be removed before rendering new html.
The global variables used are
// initially html is not generated.
var htmlGenerated = false;
// number of inputs start out as 2.
var numberOfInputs = 2;
// initially no addtional inputs have been added.
var addMore = false;
// initially html is not rendered
var htmlRendered = false;
I've created three methods for accomplishing this goal.
generate_html()
add_more()
render_html()
There is a reset function that should remove the controls, the textarea, and the rendered html.
function generate_html() {
//have we added more?
if(addMore && htmlGenerated){
// then delete the old textarea.
textarea = document.getElementById("generated_html_textarea");
textarea.remove();
// delete the controls.
controls = document.getElementById("program1");
controls.remove();
}
//has the html already been generated?
if(!htmlGenerated){
const e_inputs = document.querySelectorAll("[id^='el']");
const d_inputs = document.querySelectorAll("[id^='dl']");
const title = document.getElementById('title_input').value;
let elArray = [];
let dlArray = [];
e_inputs.forEach( i => { if(i.value) elArray.push(i.value) });
d_inputs.forEach( i => { if(i.value) dlArray.push(i.value) });
let text = title + "\n";
for (let i = numberOfInputs; i < elArray.length; i++) {
text += `${elArray[i]}:${dlArray[i]}\n`;
}
//fetch the results box
results = document.getElementById("results");
//create textarea
textarea = document.createElement("textarea");
textarea.setAttribute("id","generated_html_textarea");
// initialize blank html
html = '';
//create key inputs
for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){
html += '<div id="s';
id = (1+i-numberOfInputs);
html += id;
html +='\" class=\"draggyBox-small\">';
html += elArray[i-numberOfInputs];
html +='</div>\n';
}
//create description inputs
html += '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < dlArray.length+numberOfInputs; i++){
html += '<td id="row';
id = (1+i-numberOfInputs);
html += id;
html +='">\n';
html += '\t\t<div id=\"t';
html +=i-numberOfInputs;
html +='" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html +=dlArray[i-numberOfInputs];
html +='</td >\n </tr>\n';
}
html += '</table>';
// html generation is done.
htmlGenerated = true;
textarea.value = html;
results.appendChild(textarea);
// Generate reset, show answer, , and render html buttons
controls = document.createElement("div");
controls.setAttribute("id","program1");
controls.setAttribute("style","border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
controls.innerHTML += '<span style="padding: 3px"> <button id ="one" class="button" type="button" onClick="one()">Show Answer</button> <button id = "resetButton" class="button" type="button" onClick="reset()">Reset</button><button id = "renderHTMLButton" class="button" type="button" onClick="render_html()">Render html</button> <span id = "audio" style=""> <img id="bg" src="audioOff.png" height="30" width="30" style="margin-bottom:-10px; padding-bottom:-20px;"/> </span> </span>';
results.appendChild(controls);
}
}
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
//create a new row for a key term.
row = document.createElement("div");
row.setAttribute("class","row");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML +=numberOfInputs;
row.innerHTML +=" :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id","el"+numberOfInputs);
//add the key to the row.
row.appendChild(key);
//create a row for the new description.
row2 = document.createElement("div");
row2.setAttribute("class","row");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML+=numberOfInputs;
row2.innerHTML+=" :";
// create the description input
description = document.createElement("input");
description.setAttribute("id","dl"+numberOfInputs);
// add the description to the row.
row2.appendChild(description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
function render_html(){
// was html rendered?
if(!htmlRendered){
textarea = document.getElementById("generated_html_textarea");
generated_html = textarea.value;
console.log(generated_html);
maincontentstyle = document.getElementById("maincontentstyle");
rendered_html = document.createElement("div");
rendered_html.setAttribute("id","rendered_html");
rendered_html.setAttribute("style","border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
rendered_html.innerHTML += generated_html;
maincontentstyle.appendChild(rendered_html);
htmlRendered = true;
}
}
function reset() {
// reset the htmGenerated to false.
htmlGenerated = false;
htmlRendered = false;
numberOfInputs = 2;
var someVarName = true;
sessionStorage.setItem("someVarKey1", someVarName);
window.location.reload();
}
The issue that I'm facing is
When the user clicks generate html with the initial inputs set to valid values the generated html is created properly. When the user clicks add more and then clicks generated html a second div with a second textarea and second set of controls are created. This should not happen. The original textarea and controls should be replaced.
Any help with this would be greatly appreciated.

In add_more(), comment out the htmlGenerated = false; line (since clicking the "add more" button doesn't remove the generated html) and in generate_html() add htmlGenerated = false; after controls.remove();.
// initially html is not generated.
var htmlGenerated = false;
// number of inputs start out as 2.
var numberOfInputs = 2;
// initially no addtional inputs have been added.
var addMore = false;
// initially html is not rendered
var htmlRendered = false;
function generate_html() {
//have we added more?
if (addMore && htmlGenerated) {
// then delete the old textarea.
textarea = document.getElementById("generated_html_textarea");
textarea.remove();
// delete the controls.
controls = document.getElementById("program1");
controls.remove();
htmlGenerated = false;
}
//has the html already been generated?
if (!htmlGenerated) {
const e_inputs = document.querySelectorAll("[id^='el']");
const d_inputs = document.querySelectorAll("[id^='dl']");
const title = document.getElementById('title_input').value;
let elArray = [];
let dlArray = [];
e_inputs.forEach(i => {
if (i.value) elArray.push(i.value)
});
d_inputs.forEach(i => {
if (i.value) dlArray.push(i.value)
});
let text = title + "\n";
for (let i = numberOfInputs; i < elArray.length; i++) {
text += `${elArray[i]}:${dlArray[i]}\n`;
}
//fetch the results box
results = document.getElementById("results");
//create textarea
textarea = document.createElement("textarea");
textarea.setAttribute("id", "generated_html_textarea");
// initialize blank html
html = '';
//create key inputs
for (let i = numberOfInputs; i < elArray.length + numberOfInputs; i++) {
html += '<div id="s';
id = (1 + i - numberOfInputs);
html += id;
html += '\" class=\"draggyBox-small\">';
html += elArray[i - numberOfInputs];
html += '</div>\n';
}
//create description inputs
html += '<table id=\"tablestyle\">'
for (let i = numberOfInputs; i < dlArray.length + numberOfInputs; i++) {
html += '<td id="row';
id = (1 + i - numberOfInputs);
html += id;
html += '">\n';
html += '\t\t<div id=\"t';
html += i - numberOfInputs;
html += '" class=\"ltarget\"></div>\n \t</td >\n \t<td id=\"d2\">'
html += dlArray[i - numberOfInputs];
html += '</td >\n </tr>\n';
}
html += '</table>';
// html generation is done.
htmlGenerated = true;
textarea.value = html;
results.appendChild(textarea);
// Generate reset, show answer, , and render html buttons
controls = document.createElement("div");
controls.setAttribute("id", "program1");
controls.setAttribute("style", "border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
controls.innerHTML += '<span style="padding: 3px"> <button id ="one" class="button" type="button" onClick="one()">Show Answer</button> <button id = "resetButton" class="button" type="button" onClick="reset()">Reset</button><button id = "renderHTMLButton" class="button" type="button" onClick="render_html()">Render html</button> <span id = "audio" style=""> <img id="bg" src="audioOff.png" height="30" width="30" style="margin-bottom:-10px; padding-bottom:-20px;"/> </span> </span>';
results.appendChild(controls);
}
}
function add_more() {
// we've added more inputs.
addMore = true;
// set html generated to false, because new inputs have been added.
// htmlGenerated = false;
// increment the number of inputs.
numberOfInputs++;
//fetch the input boxes.
inputs = document.getElementById("inputBoxes");
//create a new row for a key term.
row = document.createElement("div");
row.setAttribute("class", "row");
// set the key term text.
row.innerHTML = "Key Term ";
row.innerHTML += numberOfInputs;
row.innerHTML += " :";
// create the input for the key.
key = document.createElement("input");
key.setAttribute("id", "el" + numberOfInputs);
//add the key to the row.
row.appendChild(key);
//create a row for the new description.
row2 = document.createElement("div");
row2.setAttribute("class", "row");
// set the description text.
row2.innerHTML = "Description "
row2.innerHTML += numberOfInputs;
row2.innerHTML += " :";
// create the description input
description = document.createElement("input");
description.setAttribute("id", "dl" + numberOfInputs);
// add the description to the row.
row2.appendChild(description);
// add the rows for the key and the description to the inputBoxes.
inputs.appendChild(row);
inputs.appendChild(row2);
}
function render_html() {
// was html rendered?
if (!htmlRendered) {
textarea = document.getElementById("generated_html_textarea");
generated_html = textarea.value;
console.log(generated_html);
maincontentstyle = document.getElementById("maincontentstyle");
rendered_html = document.createElement("div");
rendered_html.setAttribute("id", "rendered_html");
rendered_html.setAttribute("style", "border: 1px solid #EB0D1B; width: 360px; font-family: courier; font-size: 100.5%; margin: 0px auto; border: 1px; text-align: center; margin-top: 5px;");
rendered_html.innerHTML += generated_html;
maincontentstyle.appendChild(rendered_html);
htmlRendered = true;
}
}
function reset() {
// reset the htmGenerated to false.
htmlGenerated = false;
htmlRendered = false;
numberOfInputs = 2;
var someVarName = true;
sessionStorage.setItem("someVarKey1", someVarName);
window.location.reload();
}
<div id="inputBoxes" class="inputBoxes">
<title>Input:</title>
<div class="row">
Title: <input id= "title_input" type="text" value="t">
</div>
<div class="row">
Key Term 1: <input id="el1" type="text" value="k1">
</div>
<div class="row">
Description 1: <input id="dl1" type="text" value="d1">
</div>
<div class="row">
Key Term 2: <input id="el2" type="text" value="k2">
</div>
<div class="row">
Description 2: <input id="dl2" type="text" value="d2">
</div>
</div>
<div>
<button onClick="generate_html()">Generate</button>
<button onClick="add_more()">More</button>
</div>
<div id="results"></div>
<div id="maincontentstyle"></div>

Related

Display slider when you hover over array elements and give value to the array elements

I have done the part where you have to generate the array elements when you enter them from textbox, what I struggle with now is to display a slider on hover over each array element and give the array element a value, also what I struggle with is to delete each generated array element individually, my delete function deletes the entire array on click not just the single element I click.
Here is how it should look like:
enter image description here
Here is my code so far:
let names = [];
let nameInput = document.getElementById("name");
let messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
clearAndShow();
}
function remove()
{
var element = document.getElementById("display");
element.parentNode.removeChild(element);
}
function clearAndShow () {
let printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.style.borderStyle = "solid"
_span.style.borderColor = "blue"
_span.style.width = '50px'
_span.style.marginLeft = "5px"
_span.appendChild(document.createTextNode(element))
messageBox.appendChild(_span)
printd +="''" + element + "''" + "," + " ";
document.getElementById("labelprint").innerHTML=(printd)
}
})
}
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
<div class="container">
<form>
<h1>Enter Search</h1>
<input id="name" type="text" />
<input type="button" value="Search" onclick="insert()" />
</form>
<br/>
<div onclick="remove(this)" id="display"></div>
<br/>
<label >You have Selected: </label>
<h3 id="labelprint"></h3>
</div>
I am not being rude I just got confused on how you stated your message but what I think you are saying is to do this:
var names = [];
var nameInput = document.getElementById("name");
var messageBox = document.getElementById("display");
function insert ( ) {
names.push( nameInput.value );
// add value to array val: names[names.length - 1] = PutValueHere
clearAndShow();
}
function remove(this){
document.getElementById("display").parentNode.firstChild.remove(); // If you want it to remove the last child with the id 'display' then do .parentNode.lastChild.remove()
//if you are trying to remove the last val in the array do this: names.splice(names.length-1,1) for the first do this names.splice(0,1)
}
function clearAndShow () {
var printd=""
nameInput.value = "";
messageBox.innerHTML = "";
names.forEach(function(element){
if(element != ''){
var _span = document.createElement('span');
_span.id = '_spanId'
$('_spanId').css('border-style',solid');
$('_spanId').css('border-color',blue');
$('_spanId').css('width',50+'px');
$('_spanId').css('margin-left',5+'px');
_span[0].appendChild(document.createTextNode(element))
messageBox[0].appendChild(_span)
printd += "''" + element + "'', ";
document.getElementById("labelprint").innerHTML = printd
}
})
}
I have tried to implement something that i hope it's close to what are you looking for:
HTML:
<div class="container">
<form>
<h1>Add new slider</h1>
<input id="sliderName" type="text" />
<input type="button" value="Add" onclick="insertSlider()" />
</form>
<div id="display"></div>
</div>
CSS:
h3 {
color: rgb(0, 174, 255);
}
.container {
border: solid 2px;
display: block;
margin-left: 200px;
margin-right: 200px;
margin-top: 50px;
}
JS:
let messageBox = document.getElementById("display");
function deleteFn(id) {
const element = document.getElementById(id)
if(element) element.outerHTML="";
}
function onChangeSlideId(id){
const elementSlide = document.getElementById('slider-'+id+'')
if(elementSlide){
const value = elementSlide.value
const elementSlideText = document.getElementById('slider-value-'+id+'')
elementSlideText.innerText = '('+value+')'
}
}
function insertSlider(){
const name = document.getElementById("sliderName")
const nameValue = name.value
const newLabel = document.createElement('label')
newLabel.setAttribute('for',nameValue)
newLabel.innerText = nameValue
const newSlider = document.createElement('input')
newSlider.setAttribute('id','slider-'+nameValue+'')
newSlider.setAttribute('type','range')
newSlider.setAttribute('name',nameValue)
newSlider.setAttribute('onchange','onChangeSlideId("'+nameValue+'")')
const sliderValue = document.createElement('span')
sliderValue.setAttribute('id','slider-value-'+nameValue+'')
sliderValue.innerText = '('+newSlider.value+')'
const newContainer = document.createElement('div')
newContainer.setAttribute('id',nameValue)
newContainer.setAttribute('style','display: grid')
newContainer.appendChild(newSlider)
newContainer.appendChild(newLabel)
newContainer.appendChild(sliderValue)
const newDeleteButton = document.createElement('input')
newDeleteButton.setAttribute('type', 'button')
newDeleteButton.setAttribute('value', 'Delete ' + nameValue + '')
newDeleteButton.setAttribute('onclick', 'deleteFn("'+nameValue+'")')
newContainer.appendChild(newDeleteButton)
messageBox.appendChild(newContainer)
}
You can try it by yourself in this codepen

Want to remove previously appended table

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>
Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Using InnerHTML on 144 different cells

I am creating a tile based game using tables. In each td cell,
<td>
<div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/></div>
<input id ="attap" type="submit" value="Show Div" onclick="showDiv(); if(submitted)this.disabled = true" />
<div id="welcomeDiv" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv3(); if(submitted)this.disabled = true" /></div>
<div id="welcomeDiv3" style="display:none;"> <input type="submit" name="answer" value="Show Div" onclick="showDiv4(); if(submitted)this.disabled = true"" /></div>
<div id= "welcomeDiv4" style="display:none;"><input type="submit" name="answer" value="Show Div" onclick="showDiv5(); if(submitted)this.disabled = true"" /> </div>
</td>
Javascipt:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
document.getElementById('image').style.display = "block";
submitted = true;
populationred +=20;
document.getElementById('population').innerHTML = populationred;
}
function showDiv3() {
document.getElementById('welcomeDiv3').style.display = "block";
document.getElementById("image").innerHTML = "'<img src='http://www.sgshophouses.com/images/Shophouses1.jpg'>'"
submitted = true;
populationred +=50;
document.getElementById('population').innerHTML = populationred;
}
function showDiv4() {
document.getElementById('welcomeDiv4').style.display = "block";
document.getElementById('image').innerHTML = "'<img src='http://singaporepropertylaunch.com.sg/wp-content/uploads/2015/04/HDB-resale-prices-fall-1.0.gif'>'"
submitted = true;
populationred +=100;
document.getElementById('population').innerHTML = populationred;
}
function showDiv5() {
document.getElementById('image').innerHTML = "'<img src='www.realestatechannel.com/assets_c/2010/06/Austonian-Condo-Tower-thumb- 120x238.jpg'>'"
submitted = true;
populationred +=200;
document.getElementById('population').innerHTML = populationred;
}
I need to repeat this for 144 cells. However, the problem is that when 1 button is clicked, the image will show up only at the first cell, hence the tedious way of solving this issue is to rename all the divs differently for every cell. Is there any more efficient ways?
You can refer here: www2.hci.edu.sg/t0104448b/cells.html for a "fiddle".
Shilly's comment had the right idea. I'm not entirely sure what your goal is but this is what I did, that looks reasonably what you're after. It should get you started.
There's only one click handler, on the <table> itself. It's effectively delegating the click. This saves memory because you're not creating a copy/closure for every cell. It costs some performance due to the delegating nature but for click handlers, it's generally okay. For mouseover handlers, that's another subject.
Using a <template> tag effectively gives you a DocumentFragment to work with and markup as HTML, instead of doing it in JavaScript (which can be tedious).
We clone that document fragment 144 times, injecting the proper description ('ShopHouse', 'HDB Flat', 'Condo', etc.) into each stamp of the template. Each clone is appended to a document fragment. Once our document fragment is done being modified, we inject it into the DOM via board.appendChild(frag);.
var board = document.getElementById('board');
var cellTmpl = document.getElementById('template-cell');
var cellTmplContent = cellTmpl.content;
var frag = document.createDocumentFragment(); // for performance
var submitted = false; // not sure what you intend to use this for
var descriptions = [ 'ShopHouse', 'HDB Flat', 'Condo' ]; // ... etc.
var cells = [];
for (var r = 0; r < 12; r++) {
var row = [];
cells.push(row);
var tr = document.createElement('tr');
frag.appendChild(tr);
for (var c = 0; c < 12; c++) {
var clone = document.importNode(cellTmplContent, true);
var index = r * 12 + c;
var description = index < descriptions.length ? descriptions[index] : 'Unknown place';
clone.querySelector('p.description').innerText = description;
tr.appendChild(clone);
row.push(clone);
}
}
board.appendChild(frag);
board.addEventListener('click', function(e) {
var button = e.target;
var td = button.parentElement;
var img = td.querySelector('img');
var p = td.querySelector('p.description');
button.disabled = true;
img.style.display = 'block';
p.style.display = 'block';
submitted = true;
});
// could do something with `cells` variable if you like. It's a two dimensional array of <td> elements
td {
background: #ccc;
border: 1px solid #000;
}
td > img {
display: none;
zoom: 0.2;
}
p.description {
display: none;
}
<table id="board">
</table>
<template id="template-cell">
<td>
<img src="http://thumb7.shutterstock.com/display_pic_with_logo/339217/339217,1272881114,1/stock-vector-hand-drawing-of-typical-house-along-the-canal-near-bangkok-in-thailand-52242874.jpgAttap"/>
<button>Show</button>
<p class="description"></p>
</td>
</template>

Categories

Resources