Javascript search and display divs with matching keywords - javascript

What I'm looking for:
I'm working on creating an easy way for a user to search a list of people, and for results to instantly display below the search field. The results MUST display "close" results, rather than exact. For example: User searches for "Mr. Smith" and The following existing result is displayed: "John Smith" (since there is no "Mr. Smith" entry, it displayed one with the keyword "smith")
What I have:
I have a working code that lets the user enter some characters and all divs that include a string matching the input is displayed (see in jsfiddle: http://jsfiddle.net/891nvajb/5/ Code is also below)
Unfortunately, this only displays results that match EXACTLY.
<body>
<input type="text" id="edit_search" onkeyup="javascript: find_my_div();">
<input type="button" onClick="javascript: find_my_div();" value="Find">
<script>
function gid(a_id) {
return document.getElementById (a_id) ;
}
function close_all(){
for (i=0;i<999; i++) {
var o = gid("user_"+i);
if (o) {
o.style.display = "none";
}
}
}
function find_my_div(){
close_all();
var o_edit = gid("edit_search");
var str_needle = edit_search.value;
str_needle = str_needle.toUpperCase();
if (str_needle != "") {
for (i=0;i<999; i++) {
var o = gid("user_"+i);
if (o) {
var str_haystack = o.innerHTML.toUpperCase();
if (str_haystack.indexOf(str_needle) ==-1) {
// not found, do nothing
}
else{
o.style.display = "block";
}
}
}
}
}
</script>
<div id="user_0" style="display:none">Andy Daulton<br/>Owner Nissan<br/><br/></div>
<div id="user_1" style="display:none">Doug Guy<br/>Bug Collector<br/><br/></div>
<div id="user_2" style="display:none">Sam Hilton<br/>Famous Celebrity in Hollywood<br/><br/></div>
<div id="user_3" style="display:none">Don Grey<br/>Old man<br/><br/></div>
<div id="user_4" style="display:none">Amy Hinterly<br/>Cook<br/><br/></div>
<div id="user_5" style="display:none">Gary Doll<br/>Racecar Driver<br/><br/></div>
<div id="user_6" style="display:none">Tod Akers<br/>Football Player<br/><br/></div>
<div id="user_7" style="display:none">Greg Barkley<br/>Interior designer<br/><br/></div>
<div id="user_8" style="display:none">Alen Simmons<br/>8th place winner<br/><br/></div>

Split the words in the search string with a regex like
searchString.split(/\W/);
and do a OR search over each of the words in the resulting array.
Updated fiddle
var searchStrings = str_needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toUpperCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName("name");
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].style.display = "block";
}
}
}
}

One further approach, is as follows:
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
// applies the Array.prototype.forEach() method to the array-like nodeList
// returned by document.querySelectorAll() (the string passed to which finds all
// elements with an id that starts with ('^=') the string 'user_':
[].forEach.call(document.querySelectorAll('[id^=user_]'), function(div) {
// 'div' is the array element (the node) itself:
div.style.display = 'none';
});
}
function find_my_div() {
close_all();
// getting the trimmed lower-cased string from the input element, split
// on white-space characters to create an array:
var keywords = gid('edit_search').value.trim().toLowerCase().split(/\s+/),
// as above, selecting all elements whose id starts with the string 'user_':
haystack = document.querySelectorAll('[id^="user_"]'),
// working out whether text is accessed by node.textContent, or node.innerText:
textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
// an initialised variable, for later:
userWords,
// filters the haystack (the divs whose id starts with 'user_'):
found = [].filter.call(haystack, function(user) {
// assigns the lower-cased string to the created-variable:
userWords = user[textProp].toLowerCase();
// returns those div elements whose text contains some of
// the words returned, earlier, as the keywords:
return keywords.some(function (word) {
return userWords.indexOf(word) > -1;
});
});
// iterates over the found elements, and shows them:
[].forEach.call(found, function(user) {
user.style.display = 'block';
});
}
<body>
<input type="text" id="edit_search" onkeyup="javascript: find_my_div();">
<input type="button" onClick="javascript: find_my_div();" value="Find">
<script>
function gid(a_id) {
return document.getElementById(a_id);
}
function close_all() {
[].forEach.call(document.querySelectorAll('[id^=user_]'), function(div) {
div.style.display = 'none';
});
}
function find_my_div() {
close_all();
var keywords = gid('edit_search').value.trim().toLowerCase().split(/\s+/),
haystack = document.querySelectorAll('[id^="user_"]'),
textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
userWords,
found = [].filter.call(haystack, function(user) {
userWords = user[textProp].toLowerCase();
return keywords.some(function (word) {
return userWords.indexOf(word) > -1;
});
});
console.log(found);
[].forEach.call(found, function(user) {
user.style.display = 'block';
});
}
</script>
<div id="user_0" style="display:none">Andy Daulton
<br/>Owner Nissan
<br/>
<br/>
</div>
<div id="user_1" style="display:none">Doug Guy
<br/>Bug Collector
<br/>
<br/>
</div>
<div id="user_2" style="display:none">Sam Hilton
<br/>Famous Celebrity in Hollywood
<br/>
<br/>
</div>
<div id="user_3" style="display:none">Don Grey
<br/>Old man
<br/>
<br/>
</div>
<div id="user_4" style="display:none">Amy Hinterly
<br/>Cook
<br/>
<br/>
</div>
<div id="user_5" style="display:none">Gary Doll
<br/>Racecar Driver
<br/>
<br/>
</div>
<div id="user_6" style="display:none">Tod Akers
<br/>Football Player
<br/>
<br/>
</div>
<div id="user_7" style="display:none">Greg Barkley
<br/>Interior designer
<br/>
<br/>
</div>
<div id="user_8" style="display:none">Alen Simmons
<br/>8th place winner
<br/>
<br/>
</div>
References:
CSS:
Attribute-presence and value selectors.
JavaScript:
Array.prototype.every().
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.some().
document.querySelectorAll().
Function.prototype.call().
String.prototype.indexOf()

Related

input value to object and then that object push to array

Hollow i have some issue and small problem
i have 3 input fields I need to get values on click from them assign them to object and that object push in to array
can somebody can help ore say where to look info I'm searching on MDN but I can't find correct topic whit examples
1)input value to object and then that object push to array
function $(e) {
return document.querySelector(e);
}
function $$(e) {
return document.querySelectorAll(e);
}
var startBtn = $("send");
startBtn.addEventListener('click', creatTask, false);
function creatTask() {
var addTaskName = $(".task-name"),
addCategory = $(".category"),
addTaskSatus = $(".status");
<!-- task.Taskname = addTaskName.value
task.Category = addCategory.value
task.Status = addTaskSatus.value........... ? -- >
var TaskListArray = [];
var task = {
Taskname: undefined,
Category: undefined,
Status: undefined
}
console.log(task)
}
document.write("message")
Link to jsfiddle with html and javascript
Try setting id or className selector at var startBtn = $("send"); defining TaskListArray outside of creatTask function; setting values directly at creation of task object; use Array.prototype.push() to add current task object to TaskListArray array.
Also, use window.onload event, or place <script> after elements in html for elements queried in DOM to be loaded in document before creatTask is called or startBtn defined
<script>
window.onload = function() {
function $(e) {
return document.querySelector(e);
}
function $$(e) {
return document.querySelectorAll(e);
}
var startBtn = $(".send");
var TaskListArray = [];
startBtn.addEventListener('click', creatTask, false);
function creatTask() {
var addTaskName = $(".task-name"),
addCategory = $(".category"),
addTaskSatus = $(".status");
var task = {
Taskname: addTaskName.value,
Category: addCategory.value,
Status: addTaskSatus.value
}
TaskListArray.push(task)
console.log(task)
}
}
// document.write("message")
</script>
<input class="task-name" name="task" />
<br>
<input class="category" name="category" />
<br>
<input class="status" name="status" />
<br>
<input type="button" class="send" value="send" />

Couldn't append span element to array object in Angularjs/Jquery

Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>

I have difficulties making the button work

I have a textbox that matches the word written to id's of hidden containers and fades them in after pressing enter, everything works great except of when i added a button to make the same action...I can't seem to make the button work.
jsFIDDLE
HTML
<input type="text" value="Type the desired page" id="search" class="txtfield" onBlur="javascript:if(this.value==''){this.value=this.defaultValue;}" onFocus="javascript:if(this.value==this.defaultValue){this.value='';}" autocomplete="off"/>
<input type="button" class="btn"/>
<div class="clear"></div>
<div id="content">
<div id="home">home
<br /><i>home content</i>
</div>
<div id="about">about
<br /><i>about content</i>
</div>
<div id="portfolio">portfolio
<br /><i>portfolio content</i>
</div>
<div id="hire">hire me
<br /><i>hire me content</i>
</div>
<div id="contact">contact
<br /><i>contact content</i>
</div>
</div>
Script
var substringMatcher = function (strs, q, cb) {
return (function (q, cb, name) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function (i, str) {
$("#search").val("");
if (substrRegex.test(str) || q.slice(0, 1) === str.slice(0, 1)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push(name(str));
}
});
cb(matches);
}(q, cb, function (n) {
return {
"content": n
}
}));
};
var _matches = $.map($("#content div"), function (v, k) {
return [v.id]
});
var template = {
"content": _matches
};
var search = $('#search').val().toLowerCase();
$("#content div:gt(0)").hide(0);
$('#search').focus().keyup(function (e) {
var search = $(this);
var _search = search.val();
if (e.which === 13){
substringMatcher(template.content, _search, function (d) {
$("#" + d[0].content)
.delay(500)
.fadeIn(500)
.siblings()
.fadeOut(500);
search.val("")
})
}
});
Here's a solution
http://jsfiddle.net/35r0m6rc/12/
This part got changed:
$('#search').focus().keyup(function (e) {
var search = $(this);
var _search = search.val();
if (e.which === 13){
show_page(_search);
}
});
$('.btn').click(function(){
show_page($('#search').val());
});
function show_page(_search) {
substringMatcher(template.content, _search, function (d) {
$("#" + d[0].content)
.delay(500)
.fadeIn(500)
.siblings()
.fadeOut(500);
search.val("")
})
}
I made a func to show the page, used by both RETURN and the button.

Javascript document.replaceElement() optimization

Today i got the problem to reset my <input type="file"> after uploading with XmlHttpRequest. After some search for a solution i only found jQuery related stuff, but i rather want to implement it in pure Javascript (learning). So i created a function for it, named document.replaceElement, and the alias functions document.replaceElementById and document.replaceElementsByTagName.
I want to share this functions, and my question is now: How to optimize them? I'm not a freak as some others out there, so if someone can help optimizing them, try out. I'm really interested in it.
Please to not refer to a jQuery again, i wont use it, and i know how to make this possible with jQuery...
THANK YOU
The Javascript (replace-element.js)
// define replaceElement
// param E = element to replace
// param N = replace with this element
// if not given (undefined), recreate the one from the dom!
// if empty replace with empty text node
// if given string replace with innerHTML of string
// if given as array or nodeList, replace with the full list
// param R = used to return the new element instead of replace E
// primarily used for recursive call
document.replaceElement = function(E,N,R) {
// check if given plain string
if (typeof N == 'string') {
// in case of string use innerHTML on a new Element (used <p> here)
var X = document.createElement('p');
X.innerHTML = N;
// if multiple elements are inserted, check all the nodes and push
// them to N, which will laterly be inserted using insertBefore
var S = X.firstChild;
if (S != null) {
N = [];
}
while (S != null) {
if (S.nodeType == 1) {
N.push(S);
}
S = S.nextSibling;
}
// if theres only one element, there is no need to use as array
if (N.length && N.length == 1) {
N = N[0];
}
}
// if the given replace-to value (see N parameter) is not given
// lookup the dom and recreate the element with its originial contents
else if (!N) {
// checked for elements itself here...
if (E.nodeType == 1) {
// create new element
N = document.createElement(E.nodeName);
// i needed to walk through all the attributed on the given element
// and push them to the attributes of the new element
for(var i = 0;i < E.attributes.length;i++) {
// some struggling here with .value and .nodeValue, as well as setAttribute
// and setAttributeNode here, because of different js versions
if (typeof N.setAttribute !== undefined) {
if (E.attributes[i].value) {
N.setAttribute(E.attributes[i].nodeName,E.attributes[i].value);
} else {
N.setAttribute(E.attributes[i].nodeName,E.attributes[i].nodeValue);
}
} else {
N.setAttributeNode(E.attributes[i].cloneNode(false));
}
}
// now walk the given elements child list and append them
// to the element using recursive calls for creation
var S = E.firstChild;
while (S != null) {
N.appendChild(document.replaceElement(S,undefined,true));
S = S.nextSibling;
}
}
// got some errors here, so text nodes are also checked
// and inserted with createTextNode. TODO: use .data here?
else if (E.nodeType == 3) {
N = document.createTextNode(E.nodeValue);
}
// all other types of elements are cloned directly
else {
N = E.cloneNode(true);
}
}
// check if this is not an recursive call...
if (!R) {
// if the new element has length, it is a nodeList or array!
// walking that and use insertBefore on the parent node
if (N.length !== undefined) {
for (i=0;i<N.length;i++) {
E.parentNode.insertBefore(N[i],E);
}
// the original element is deleted if empty string given
E.parentNode.removeChild(E);
} else {
// the given element is replaced with the new one using replaceChild...
E.parentNode.replaceChild(N,E);
}
}
return N;
}
// simple *ById implementation for replaceElement
document.replaceElementById = function(E,C) {
return document.replaceElement(document.getElementById(E),C);
}
// another simple *ByName for replaceElement
document.replaceElementsByName = function(E,C) {
E = document.getElementsByName(E);
var Z = [];
for (var i=0;i<E.length;i++) {
Z.push(document.replaceElement(E[i],C));
}
return Z;
}
HTML Code (replace-element.html)
<html>
<head>
<meta charset="utf-8">
<title>Test replaceElement</title>
<script type="text/javascript" src="replace-element.js"></script>
</head>
<body>
<div id="my-div" name="named-div">
<input type="file" id="my-button" name="named-button" multiple="true" />
<input type="text" value="" placeholder="type in text" />
</div>
<br /><br />
<button onclick="document.replaceElementById('my-button')">replace BUTTON by id</button>
<button onclick="document.replaceElementsByName('named-button')">replace BUTTON by name</button>
<br /><br />
<button onclick="document.replaceElementById('my-div')">replace DIV by id</button>
<button onclick="document.replaceElementsByName('named-div')">replace DIV by name</button>
<br /><br />
<button onclick="document.replaceElementById('my-div','<p>YES, <strong>REPLACED</strong>!</p>')">replace DIV by p tag</button>
<button onclick="document.replaceElementsByName('named-div','<p>YES, <strong>REPLACED</strong>!</p>')">replace DIV by p tag</button>
<br /><br />
<button onclick="document.replaceElementById('my-button','')">delete BUTTON by id</button>
<button onclick="document.replaceElementsByName('named-button','')">delete BUTTON by name</button>
<button onclick="document.replaceElementById('my-div','')">delete DIV by id</button>
<button onclick="document.replaceElementsByName('named-div','')">delete DIV by name</button>
</body>
</html>

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