How to search page for words and highlight them (JQuery) - javascript

I currently have an array of user inputted words and respective highlight colors stored in objects (below is the function that constructs the array upon user button click and input):
//DECLERATIONS////
var placementId = 0;
var searchList = [];
///FUNCTION THAT ADDS A NEW WORD TO SEARCHLIST////////
function addWord(userWord, userColor){ //append new word to find and highlight
var wordAndColorPair = {
word: userWord,
color: userColor,
id: placementId
}
searchList.push(wordAndColorPair);
}
///////BELOW IS THE EVENT THAT ACTUALLY CONSTRUCTS THE ARRAY//////////
$('.color-element').click(function(){ //adding new word-color pairs
var userInput = $('#input-word').val();
if(userInput !== ''){ //only if user enteres text:
var newWord = document.createElement("span"); //create a new search word tile
newWord.classList.add('search-word'); //add the class search-word to it
newWord.textContent = userInput; //make its text value equal to the input
var colorId = $(this).attr('id'); //set its bacckground color to a copy of the button clicked
$(newWord).css("background-color", colorId);
$(newWord).attr('id', placementId); //set this new elements unique ID for delection purposes
$('.display-array').append(newWord); //append the child to the DOM
addWord(userInput, colorId, placementId); //add the word to the search list - increment placementId for future words
placementId ++;
$('#input-word').val(''); //reset the input field
}
else{
return;
}
});
What I am having trouble with is being able to search the whole page and actually highlight the words seen in the array. What I have so far is:
$('.search').click(function(){ //when the search button is clicked
var i;
for(i =0; i< searchList.length; i++){//for each word user inputted:
$("*").contents().each(function() {
var word = searchList[i].word;
var regex = new RegExp('(\\b'+word+'\\b)', 'gi');
if(this.nodeType == 3){ //if text
$(this).html(text.replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'> " + searchList[i].word + "</span>"));
}
});
}
});
This, however, does not seem to be working, any assistance is much appreciated!
HTML for DOM reference:
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Changa:700|Roboto+Condensed:700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type = "text/javascript" src="popup.js"></script>
<meta charset="utf-8">
<title>Word Finder</title>
<link rel="stylesheet" href="style.css" media="screen">
<meta name="description" content="Word Finder Chrome Extension">
<meta name="author" content="Aalok Borkar">
</head>
<body>
<p>
this is a test of the funcitonality TEXT text text text hello
</p>
<div class = "input">
<div class = "word">
Word <input type = "text" id = 'input-word' placeholder= "Jim Halpert"></input>
</div>
<div class = "color-palette">
<!-- on click: clear text input, add color, append search array / display array -->
<button class = "color-element" id = "red"></button>
<button class = "color-element" id = "orange"></button>
<button class = "color-element" id = "yellow"></button>
<button class = "color-element" id = "green"></button>
<button class = "color-element" id = "blue"></button>
<button class = "color-element" id = "violet"></button>
<button class = "color-element" id = "pink"></button>
</div>
</div>
<div class = "display">
<p> Words to Search</p>
<div class = "display-array">
</div>
</div>
<button class = "search">Search</button>
</body>
</html>

It need to be done that way:
$(this).parent().html($(this).parent().html().replace($(this).text(),$(this).text().replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'>" + searchList[i].word + "</span> ")));
This is because when you change the innerHTML directly you will mess the dom structure and lose the html format, when you change the text solely you would have a a sanitized DOM inside quotes, so it should be solved one way by modifying the text part inside the inner html.
see it here

I added a class to your <p> element, but you probably don't have to do that. I just did it for ease of access on my part. The biggest thing, if I understood your question right, was your search function. IMO, you need to look at each word and compare it to the search array. Find the word that matches and wrap it in something that you can apply a style to. In my case, I chose a <span> tag. Fiddle below code.
// HTML Modification
<p class="searchable">
this is a test of the functionality TEXT text text text hello
</p>
$('.search').click(function() { //when the search button is clicked
var original = $('.searchable').html().trim();
var searchable = original.split(" ");
for (var i = 0; i < searchList.length; i++) { //for each word user
inputted:
for (var s = 0; s < searchable.length; s++) {
if (searchable[s] == searchList[i].word) {
searchable[s] = "<span style='background:" + searchList[i].color +
";'>" + searchList[i].word + "</span>";
}
}
}
rewrite(searchable); //SEE BELOW
});
// This iterates over the searchable array
function rewrite(searchable) {
var highlighted = "";
for (var i = 0; i < searchable.length; i++) {
highlighted += searchable[i] + " ";
}
$('.searchable').html(highlighted.trim());
}
https://jsfiddle.net/5v3aqrzd/

Related

Get individual input values from dynamic input fields

After creating dynamic inputs along with its dynamic id's by append, only the latest generated input field gives values
Other dynamic input fields return empty string
Note: I'm able to get all values of dynamic inputs by using for loop and pushing inside an array, but i also want to get each input individually on key up . But only final input field created gives value
Here is my fiddle,
https://jsfiddle.net/xd8nvktf/3/
Not able to come up with a solution, Help is appreciated
--Thanks
HTML
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<button type = "button" class = "btn btn-primary" id = "addInput">Add Input Fields</button>
<div id = "inputAdder">
</div>
</body>
JS/JQUERY
var a = 0;
var fieldValue;
var dataStored = [];
var valueStored = [];
$("#addInput").on("click", function() {
a += 1;
fieldValue = `#filter-value${a}`;
$("#inputAdder").append(
`<div class = "row" id="appender${a}">
<div class="col-md-4 padderSpace">
<input id="filter-value${a}">
</div>
</div>`
)
dataStored.push({value:fieldValue});
console.log(dataStored)
})
$("#inputAdder").on("keyup",fieldValue,changeFunc);
function changeFunc(){
console.log($(fieldValue).val());
valueStored = [];
for(let i = 0;i<=dataStored.length;i++){
valueStored.push({value:$(dataStored[i].value).val()})
console.log(valueStored)
}
}
You need to pass current textbox id to your changeFunc function.
function changeFunc(e){
console.log($("#" + e.target.id).val());
}
Here is working sample.

change text multiple times with a single button and hide the button for the last text

I want to write a basic story where you just click next and the text changes.
I can change the text, but I don't know how to hide the button. Basically I want the onclick method to execute multiple functions, but not all at the same time, rather in a sequence
Code as below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="div1">
<p id="txt" class="txt1">OK, here wo go.</p>
</div>
<button id="btn_next" type="button">Next</button>
<script>
document.getElementById("btn_next").addEventListener("click", toggleText);
function toggleText() {
var textBox = document.getElementById("txt");
switch (textBox.className) {
case "txt1": {
textBox.innerHTML = "This is text 1";
swapClasses(textBox, "txt2");
break;
}
case "txt2": {
textBox.innerHTML = "This is text 2";
break;
}
}
}
function swapClasses(elem, targetClass) {
elem.className = targetClass;
}
</script>
</body>
</html>
If you want to hide the button when the <p> class is txt2, which means the last text is shown, a simple way to do it would be this:
case "txt2": {
textBox.innerHTML = "This is text 2"
document.getElementById("btn_next").style.display = "none";
break;
}
You could also store the button element to a variable const btnEl = document.getElementById("btn_next") so you don't get it twice.
You can hide an element by setting its display to none like:
`nextBtn.style.display = 'none';
However, instead of using a switch statement, you can use an array of text values to drive your story as in the next answer
Another approach to this is shown below.
let counter = 0;
const displayed_text = [
'Input text 1',
'Input text 2',
'Input text 3',
'Input text 4',
];
// Assign DOM elements to variables
const btn_next = document.getElementById("btn_next");
const text_display = document.getElementById("txt");
// Attach listener to button
btn_next.addEventListener("click", toggleText);
function toggleText() {
counter += 1;
if (counter <= displayed_text.length) {
// Update displayed text
text_display.innerHTML = displayed_text[counter -1];
}
if (counter === displayed_text.length) {
// Hide button
btn_next.style.display = 'none';
}
}
The main advantage of this approach is that it makes it easier to go back multiple steps if you want.
var story = [
'OK, here wo go.',
'This is text 1',
'This is text 2',
'This is text 3',
'This is text 4'
];
var nextBtn = document.getElementById("btn_next");
function changeText() {
var textBox = document.getElementById("txt");
var chapter = Number(textBox.dataset.chapter);
if (chapter < story.length - 1) {
textBox.dataset.chapter = chapter + 1;
textBox.innerHTML = story[chapter + 1];
if ((story.length - chapter) <= 2 ) {
nextBtn.style.display = 'none';
}
}
}
nextBtn.addEventListener("click", changeText);
<div id="div1">
<p id="txt" class="txt1" data-chapter="0">OK, here wo go.</p>
</div>
<button id="btn_next" type="button">Next</button>
For cases like this, it can be beneficial to store the content in an array of objects (or fetch the content as JSON etc). Then, when the event handler is fired, it can simply increment (or decrement if you wish to have forward/backward) and determine whether the button should be visible or hidden. That appears to be the direction you're heading with the above code.
Example function:
function navigatePage(el){
// Control the navigation by only allowing increment within range
if (el != null){
switch (el.target.getAttribute("id")){
case "btn_next":
if (curr_page < story.length){
curr_page++;
}
break;
case "btn_prev":
if (curr_page > 1){
curr_page--;
}
break;
default: break;
}
}
// Set the title and text to the current page contents
// Arrays are zero-indexed, so "1" is actually "0", and so on
story_title.innerHTML = story[curr_page - 1].title;
story_content.innerHTML = story[curr_page - 1].text;
// Show or hide nav buttons based on the current page
// The following syntax is basically just a fancy "if-then" done in one line
btn_prev.style.display = (curr_page > 1 ? "inline-block" : "none");
btn_next.style.display = (curr_page < story.length ? "inline-block" : "none");
// Update the page count element
page_count.innerHTML = "Page " + curr_page + " of " + story.length;
// document.getElementById("storycontent").innerHTML = curr_page + " - " + story.length;
}
Here is a working fiddle to demonstrate how it all works together:
https://jsfiddle.net/s0toz3L8/1/

My input string values will not display on my list

I want display items of an array. At the click of button I need to perform following actions:
Add an element at the beginning, end or middle of the displayed array
Sort the array
Remove duplicates from array
I managed to display the items of the array, and add new items, one by one with my Add in the Front button. But the string values won't show, all I can see are the index numbers 1., 2., 3., ect.
I tried putting the id="firsttree" in the <input type="text"> html tag, but the array would disappear when I load it on the web page.
JS
var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];
// Iterate array and display
originalArray.forEach(element => {
// Creates an Element Node with the specified name.
let listItem = document.createElement("li");
// creates a Text Node with the specified text.
let itemDescription = document.createTextNode(element);
// append: Add Item or Element
listItem.appendChild(itemDescription);
/*document.getElementById("firsttree").innerHTML = originalArray;*/
// Returns the element that has the ID attribute with the specified value and adds a node to the end of the list of children of the specified parent node
document.getElementById("firsttree").appendChild(listItem);
});
/**
* Add Items to list
*/
function addItem() {
// Unshift: Add item to beginning of list
originalArray.unshift(document.getElementById('firsttree').value);
// Making the text box empty and re-display
document.getElementById('firsttree').value = " ";
disp(); // displaying the array elements
}
/**
* Render array
*/
function disp() {
var str=" ";
str = originalArray.length + '<br> '; // break the lines to form list.
// Increment the list by 1, i++ if i is less than length
for (i=1; i < originalArray.length; i++) // Initial parameter is 1.
{
// Adding each element with key number to display string
str += i + ". "+ originalArray[i] + "<br> ";
}
// Display the elements of the array
document.getElementById('firsttree').innerHTML=str;
}
HMTL
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="activity3.css">
<!-- ol: Ordered numbered list-->
<!--<script>
/*var trees = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];*/AbortSignal
/*document.getElementById("oringinalTree").innerHTML = trees;*/
</script>-->
</head>
<body>
<h1>Array Methods</h1>
<br>
<label>
Enter new array element here
</label>
<input type="text">
<button type="button" value="Add" onclick="addItem()" >
Add in the Front
</button>
<button type="text">
Add at the End
</button>
<button type="text">
Add in the Middle
</button>
<button type="text">
Sort
</button>
<button type="text">
Remove Duplicates
</button>
<br>
</form>
<h2>List of Trees</h2>
<h3>Tree Display:</h3>
<!-- Must create div to place list under Header-->
<div class="originalArray">
<ol id="firsttree"></ol>
<!--<link rel="stylesheet" type="text/css" href="path/to/your.css" />-->
<script src="gla3.js"></script>
</div>
<h4>Sorted Tree Display:</h4>
</body>
</html>
css
h3 {
position: absolute;
left: 70px;
top: 200px;
}
h4 {
position: absolute;
left: 300px;
top: 200px;
}
.originalArray {
position: absolute;
top: 250px;
left: 50px;
}
I need to add the string from input to the array and then be displayed, but instead I start off with undefined being added to array and the rest are all blank. Plus I don't want the number of increments (12) to be seen either.
1: Add an id to your input element:
<input type="text" id="new_element">
2: Replace firsttree with new_element in this line:
originalArray.unshift(document.getElementById('new_element').value); // adding element to array
3: Start your loop with i=0 in this line:
for (let i=0; i < originalArray.length; i++)
4: Remove this line if you don't want the number of item in your array to be displayed (the 12 from your screenshot):
str = originalArray.length + '<br> ';
Nowadays, one of the most important thing when learning a new programming language certainly is to fully understand whatever code you get from stack overflow, so don't hesitate if you want me to explain any of those steps.
Here is a example with the other functions added:
var originalArray = ['spruce', 'pine', 'cedar', 'maple', 'oak', 'birch', 'aspen'];
// why not simply use your disp() function
// to display the array at first ?
disp();
// functions to add items
function addItemFront() {
originalArray.unshift(document.getElementById('new_element').value);
document.getElementById('firsttree').value = " ";
disp(); // displaying the array elements
}
function addItemEnd() {
originalArray.push(document.getElementById('new_element').value);
document.getElementById('firsttree').value = " ";
disp();
}
function addItemMiddle() {
originalArray.splice(Math.round(originalArray.length/2), 0, document.getElementById('new_element').value);
document.getElementById('firsttree').value = " ";
disp();
}
// function to remove duplicate
function removeDuplicate() {
originalArray = array_unique(originalArray);
document.getElementById('firsttree').value = " "; // Making the text box blank
disp(); // displaying the array elements
}
// more info on this one at: https://stackoverflow.com/questions/25530168/is-there-a-function-like-array-unique-in-jquery
function array_unique(array){
return array.filter(function(el, index, arr) {
return index == arr.indexOf(el);
});
}
// function to display the array
function disp() {
var str=" ";
for (i=0; i < originalArray.length; i++){
str += i + ". "+ originalArray[i] + "<br> ";
}
document.getElementById('firsttree').innerHTML=str;
}
// function to display the sorted array
function dispSorted() {
var str=" ";
var sortedArray = originalArray.sort();
for (i=0; i < sortedArray.length; i++){
str += i + ". "+ sortedArray[i] + "<br> ";
}
document.getElementById('sortedtree').innerHTML=str;
}
.originalArray {
position: absolute;
top: 250px;
left: 50px;
}
.sortedArray {
position: absolute;
top: 250px;
left: 450px;
}
<h1>Array Methods</h1>
<br>
<div class="field">Enter new array element here</div>
<input type="text" id="new_element">
<button type="button" onclick="addItemFront();">Add in the Front</button>
<button type="button" onclick="addItemEnd();">Add at the End</button>
<button type="button" onclick="addItemMiddle();">Add in the Middle</button>
<button type="button" onclick="dispSorted();">Sort</button>
<button type="button" onclick="removeDuplicate();">Remove Duplicates</button>
<br>
<h2>List of Trees</h2>
<div class="originalArray">
<h3>Tree Display:</h3>
<ol id="firsttree"></ol>
</div>
<div class="sortedArray">
<h4>Sorted Tree Display:</h4>
<ol id="sortedtree"></ol>
</div>
For the addItem() Just like #françois-huppé mentioned, you need to add an id to the input text.
function addItem() {
originalArray.unshift(document.getElementById('new_element').value);
document.getElementById('new_element').value = "";
disp();
}
function disp() {
let str = "";
for (let i = 0; i < originalArray.length; i++) {
str += `<li>${originalArray[i]}</li>`;
}
document.getElementById('firsttree').innerHTML = str;
}
On the disp() function, there are two things to note.
Since you are appending each value to an Ordered List <ol>, you don't need a line break <br> because <li> has a display-block property by default which will display each item on a new line.
You also do not need to number the items str += i + ". "+ originalArray[i] the ordered-list will number it.
You can check the working solution here https://codepen.io/sirwhite/pen/mddKxqr

getelementsbyname Return Undefined value

I'm a javascript newbie and I have try this.
<html>
<style>
#WoodNumInput {
width:40px;
}
</style>
<body>
<script>
var i;
var woodtypeAB = ["AB_W15_L100","AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4 ; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<input type = "button" value = "calculate" onclick= "Calculation()">
<div id = "Test"></div>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("woodtypeAB[3]").value;
document.getElementById("Test").innerHTML = ShowResult;
}
</script>
</body>
The value returns undefined and I still can't figure it out.
Thank in advance for your help and suggestions.
This
var ShowResult = document.getElementsByName("woodtypeAB[3]").value
should be
var ShowResult = document.getElementsByName(woodtypeAB[3])[0].value
Since "woodtypeAB[3]" is surrounded by quotation marks it will be interpreted as a string rather than the actual array value.
document.getElementsByName() returns a NodeList of elements so you will have to explicitly say that you want the first item in the NodeList, hence [0]
There are a few things wrong.
First, you're trying to get the .value from a collection instead of from individual elements.
Also, the elements you're creating have a name value of AB_... but you're trying to fetch using a very different name.
I think you perhaps thought that the woodtypeAB[3] you're fetching would somehow translate to the variable and index you used to create the element's name. That's not how it works.
When you created the element, the concatenation did not add woodtypeAB[3] as the name, but rather the value located at that index of that array. So to fetch that particular name, you'd use its array value of AB_W30_L100.
<html>
<style>
#WoodNumInput {
width: 40px;
}
</style>
<body>
<input type="button" value="calculate" onclick="Calculation()">
<div id="Test"></div>
<br>
<script>
var i;
var woodtypeAB = ["AB_W15_L100", "AB_W20_L100", "AB_W25_L100", "AB_W30_L100"];
for (i = 0; i < 4; i++) {
document.write("<div id = 'box'><input type ='number' name = '" + woodtypeAB[i] + "' id = 'WoodNumInput' value = " + i + "></div><br/>");
}
</script>
<br/>
<script>
function Calculation() {
var ShowResult = document.getElementsByName("AB_W30_L100");
if (ShowResult.length != 0) {
document.getElementById("Test").innerHTML = ShowResult[0].value;
}
}
</script>
</body>
Although something tells me that you actually are going to want to select all those input elements and perform some calculation on them. That'll require additional tweaks to your code.

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Categories

Resources