Get value from input fields through an array - javascript

I am working on a form where there user can add multiple inputs like:
<script type="text/javascript">
<!--
var counter = 0;
var limit = 4;
window.onload = moreFields;
function moreFields() {
if (counter == limit) {
alert('You have reached the limit of adding ' + counter + ' inputs');
}
else
var newFields = document.getElementById('sa-groep').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var hetId = newField[i].id
if (hetId)
newField[i].id = hetId + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
counter++;
}
This works fine, all input get their unique id, but then i figured out that to catch all the input values it is better through getElementsByClassName
so then i made this to catch the values:
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i] + "<br />");
}
}
the html code is:
<body>
<div id="sa-groep" style="display: none">
<input class="SA" id="sa_" value=" " />
<select class="RC" id="rc_">
<option>Rating</option>
<option value="excellent">Excellent</option>
<option value="good">Good</option>
<option value="ok">OK</option>
</select><br /><br />
<input type="button" value="Remove review"
onclick="this.parentNode.parentNode.removeChild(this.parentNode)" /><br /><br />
</div>
<span id="writeroot"></span>
<input type="button" onclick="moreFields()" value="Give me more fields!" />
<input type="button" onclick="getClassValue()" value="Send form" />
</body>
But the only thing it show is : 3011 contains: So what am i doing wrong?

At first look I suggest you to change document.write (which replace all the text of your document) and instead use console.log("something..") or the property innerHTML in a specific div.
document.write, as I said before, replace all the the page with the string passed.

The problem beside the curly bracket (thanks #James) was the cloning of an hidden fields wich gave an empty result at the first spot in the arrays. To delete the first element of an array i had to delete that with shift() It works, probably it can be better but this is my solution:
function getClassValue() {
var secAut = []; // array met de namen van de secundaire auteurs
var readyItems = document.getElementsByClassName('auteur');
for(var i = 0; i < readyItems.length; i++){
secAut.push(readyItems[i].value);
}
var secAutMinus = secAut.shift(); // 1 element verwijdert uit array ivm dat de eerste input leeg is (display: none)
var relCode = []; // 2e array met de relatiecodes
var relCodeready = document.getElementsByClassName('relcode');
for(var i = 0; i < relCodeready.length; i++){
relCode.push(relCodeready[i].value);
}
var relCodeMinus = relCode.shift(); // 1st element verwijderen
for(var k= 0; k < secAut.length; k++){
console.log(3012+k+ ' contains: ' + secAut[k] + ' is ' + relCode[k] + '<br/>'); // uitlezing arrays minus het eerste lege element
}
}

In this function the loop needs to start from 1 because the 0th element is the hidden (cloned) one.
function getClassValue() {
var secAut = [];
var readyItems = document.getElementsByClassName('SA');
for (var i = 1; i < readyItems.length; i++) {
secAut.push(readyItems[i].value);
document.write(3011+i+ " contains: " + secAut[i - 1] + "<br />");
}
}
There are a couple of other problems, missing curly brace after the else in moreFields.
Here's a working fiddle

Related

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

My generated french word duplicates? When it shouldn't be

I've sorted this but now it's came back on... I've tried changing the for loops but it still seems to generate duplicate French words. It's suppose to not show the french word twice in the application run.
My jsFiddle is an exact replica:
http://jsfiddle.net/jamesw1/w8p7b6p3/17/
Javascript:
//James Wainwright's Mobile Apps Assignment
//Arrays of french and english words.
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers and make sure they aren't the same as each other.
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu using for loop. This loop runs once (on document load)
document.getElementById('generatedWord').textContent = foreignWords[number];
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Output the previous.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Declare variables 'outside' the onclick function so it ensures they work correctly.
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
var counter = 0;
var outputted = '';
//Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
var guessedList = new Array(6);
var correctList = new Array(6);
var wordGenerated = new Array(6);
//On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
document.getElementById('submitAns').onclick = function () {
//Declare variables for function.
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
//Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
while(temp==correctAns){
temp = Math.floor(Math.random() * 30);
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Generate a word here. ( call wordGen() )
wordGen();
//Create dynamic select menu for options they have to choose from.
document.getElementById('generatedWord').textContent = foreignWords[number];
//Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
var correctAnswerIndex = Math.floor(Math.random() * 6);
//If it's 0...Change it.
if(correctAnswerIndex == 0)
{
correctAnswerIndex++;
}
//Create a select menu of the options...Add the correct answer randomly into the menu.
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i < RanNumbers.length; i++) {
//This randomizes where the correct answer will be.
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += "</select>";
//Outputting to the html page.
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
//Count number of guesses
numGuesses++;
//Counter for placing guessed, correct and foreign word into there arrays.
counter++;
wordGenerated[counter] = foreignWords[number];
guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
correctList[counter] = translate[number];
//Once the application has finished...It will produce the following output.
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
outputted = "<table>";
for(var d=1;d<wordGenerated.length;d++){
outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td> <td>Guessed Word: " + guessedList[d] + "</td> <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
}
outputted += "</table>";
outputted += "<style type='text/css'>#hint{ display:none; }</style>";
//Output it to the html page.
document.getElementById('details').innerHTML = outputted;
}
};
document.getElementById('hint').onclick = function () {
alert(correctAns.charAt(0));
};
Html:
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="header">
<h1>James' Translation Guessing Game</h1>
</div>
<div data-role="content" class="main">
<h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />
<!-- What question we're upto -->
<h2 id="numGuess">Question #</h2 >
<!-- The generated French Word Aswell as end of app details-->
<div align="center" class="frenchWord" style="position:">
<!--Generated french word details-->
<div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center" id="generatedWord"></div>
<br />
<br />
<!-- Show the user there guessed answers, correct and foreign word -->
<div id="details"></div>
</div>
<!-- Select menu output -->
<div align="center" id="output"></div>
<img id="hintImg" style="" src="images/hint.png" alt="Hint" />
<!-- Buttons, Call Functions -->
<button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
<input type="button" value="New Game" onClick="document.location.reload(true)">
<script>
//Simple animation
$(document).ready(function(){
$("#generatedWord").animate({
opacity: 0.8,
margin: "40px 0px 100px 0px",
width: "20%",
padding: "30px",
}, 1500 );
});
</script>
</div>
<div data-role="footer">
<h4>James Wainwright</h4>
</div>
</div>
This might do it. Before assigning a number to the RanNumbers array I delete it from the original RanNumbers array to prevent duplication. It might make more sense to just maintain a separate array of numbers to be used in the questions but I tried to change as little as possible.
Updated Fiddle
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * RanNumbers.length);
while(temp==correctAns){
temp = Math.floor(Math.random() * RanNumbers.length);
delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
}
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}

how to get checked value from two url simultaneousl

I have two buttons one for Groups and second is for Skills. when i click on groups button one popup will show and in the popup the groups are showing with checkbox. wheni select the groups and click on save button the checked groups will show on the uper of group button and popup will close.and this same is for skills button also.
My problem is that when i select groups it will show on groups button but when i select skill i lost the selected groups.
right now i am doing this:
function OnClickButton () {
var display = "";
checkboxes = document.getElementsByName("group");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display;
}
<button type="button" onclick="OnClickButton()" >Save</button>
this is for Groups.
function OnClickButton1 () {
var display1 = "";
checkboxes = document.getElementsByName("skill");
for( var i=0; i<checkboxes.length; i++){
if( checkboxes[i].checked ){
display1 += " " + checkboxes[i].value;
}
}
window.location.href='job_posting.html?data='+display1;
}
<button type="button" onclick="OnClickButton1()" >Save</button>
And this is for skills.
I get the groups and skills in the url .Not for get the url i try this
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = "";
}
}
if(!returnBool) return false;
}
function get_data()
{
var idParameter = getUrlParameters("data","",true);
var idParameter1 = getUrlParameters("data1","",true);
document.getElementById('display').innerHTML=idParameter;
document.getElementById('display1').innerHTML=idParameter1;
}
Call this on
<body onLoad="get_data();">
Thank You in advance
Victor is right, that is the way I would do it too in raw JS, only with one difference:
<button type="button" onclick="OnNameSaveClicked()" >Save</button>
<button type="button" onclick="OnSkillSaveClicked()" >Save</button>
As you can see it does the same thing so you can do:
<button type="button" onclick="handleRedirect()" >Save</button>
And you would have the same effect with a fewer lines of code.
What you want to do is something similar to the following
function handleRedirect() {
var url = 'job_posting.html?data=';
var checkboxes = document.getElementsByName('name');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
url += '&data1=';
checkboxes = document.getElementsByName('skill');
for(var i = 0; i < checkboxes.length; i++) {
if(checkboxes[i].checked){
url += checkboxes[i].value + " ";
}
}
window.location.href = url;
}
<button type="button" onclick="handleRedirect()" >Save</button>
<button type="button" onclick="handleRedirect()" >Save</button>
Hope this helps!

Using for loop to generate text boxes

I want to be able to enter a number into a text box and then on a button click generate that number of text boxes in another div tag and automatically assign the id
Something like this but not sure how to generate the text boxes and assign automatically assign the id
function textBox(selections) {
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<form><input type="text" id="1" name=""><br></form>");
}
}
Try this one:
function textBox(selections){
selections = selections*1; // Convert to int
if( selections !== selections ) throw 'Invalid argument'; // Check NaN
var container = document.getElementById('divSelections'); //Cache container.
for(var i = 0; i <= selections; i++){
var tb = document.createElement('input');
tb.type = 'text';
tb.id = 'textBox_' + i; // Set id based on "i" value
container.appendChild(tb);
}
}
A simple approach, which allows for a number to be passed or for an input element to be used:
function appendInputs(num){
var target = document.getElementById('divSelections'),
form = document.createElement('form'),
input = document.createElement('input'),
tmp;
num = typeof num == 'undefined' ? parseInt(document.getElementById('number').value, 10) : num;
for (var i = 0; i < num; i++){
tmp = input.cloneNode();
tmp.id = 'input_' + (i+1);
tmp.name = '';
tmp.type = 'text';
tmp.placeholder = tmp.id;
form.appendChild(tmp);
}
target.appendChild(form);
}
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(); // no number passed in
});
JS Fiddle demo.
Called by:
document.getElementById('create').addEventListener('click', function(e){
e.preventDefault();
appendInputs(12);
});
JS Fiddle demo.
The above JavaScript is based on the following HTML:
<label>How many inputs to create:
<input id="number" type="number" value="1" min="0" step="1" max="100" />
</label>
<button id="create">Create inputs</button>
<div id="divSelections"></div>
See below code sample :
<asp:TextBox runat="server" ID="textNumber"></asp:TextBox>
<input type="button" value="Generate" onclick="textBox();" />
<div id="divSelections">
</div>
<script type="text/javascript">
function textBox() {
var number = parseInt(document.getElementById('<%=textNumber.ClientID%>').value);
for (var i = 0; i < number; i++) {
var existingSelection = document.getElementById('divSelections').innerHTML;
document.getElementById('divSelections').innerHTML = existingSelection + '<input type="text" id="text' + i + '" name=""><br>';
}
}
</script>
Note: Above code will generate the N number of textboxes based on the number provided in textbox.
It's not recommended to user innerHTML in a loop :
Use instead :
function textBox(selections) {
var html = '';
for (i=0; i < selections +1; i++) {
html += '<form><input type="text" id="'+i+'" name=""><br></form>';
}
document.getElementById('divSelections').innerHTML = html;
}
And be carefull with single and double quotes when you use strings
You have to change some code snippets while generating texboxes, Learn use of + concatenate operator, Check code below
function textBox(selections) {
for (var i=1; i <= selections; i++) {
document.getElementById('divSelections').innerHTML += '<input type="text" id="MytxBox' + i + '" name=""><br/>';
}
}
textBox(4); //Call function
JS Fiddle
Some points to taken care of:
1) In for loop declare i with var i
2) your selection + 1 isn't good practice at all, you can always deal with <= and < according to loop's staring variable value
3) += is to append your new HTML to existing HTML.
ID should be generate manually.
var inputName = 'divSelections_' + 'text';
for (i=0; i < selections +1; i++) {
document.getElementById('divSelections').innerHTML = ("<input type='text' id= " + (inputName+i) + " name=><br>");
}
edit : code formated
Instead of using innerHTML, I would suggest you to have the below structure
HTML:
<input type="text" id="id1" />
<button id="but" onclick="addTextBox(this)">click</button>
<div id="divsection"></div>
JS:
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input'); //create input tag
text.type = "text"; //mention the type of input
text.id = "input" + i; //add id to that tag
document.getElementById('divsection').appendChild(text); //append it
}
}
JSFiddle

Javascript to alert a user that the same info has already been entered

First I should say I am a javascript newbie so forgive my ignorance.
I'm creating a form that has three functions and also uses array:
Add - To accept a name (if field left blank it should ask the user to enter a name in an alert box)
Find - To verify a name has not already been entered (in an alert box)
List - To list the names that have been entered (in an alert box)
I have the list function working (good). The alert to enter a name comes up after you enter a name as well as when you leave the field blank (not good)
and I can't get the find function to work at all.
My code is below and I've tried so many iterations and searched so many sites for help, also tried firebug; I'm hoping someone can point me in the right direction.
Untitled
<body>
<script type="text/javascript">
var a = new Array();
function list() {
var s = "";
for (i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add() {
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
if (myTextField.value == "") {
alert("Please enter a name");
return false;
}
function find() {
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
myTextField.value = "";
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField) {
alert("Sorry, the name " + a[i] + " already exists. Try again");
}
}
}
</script>
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="list()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
</body>
</html>
You have done it almost, but some lil errors.. here you can check it jsfiddle
HTML:
<input type="text" id="myText" /><br>
<input type="button" value="Add a name" class="add_button"/>
<input type="button" value="List the names" class="list_button"/>
<input type="button" value="Find" class="find_button"/>
JS:
$(".add_button").live("click", function(){
add()
});
$(".list_button").live("click", function(){
list()
});
$(".find_button").live("click", function(){
find()
});
var a = new Array();
function list()
{
var s = "";
for(i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
a[a.length] = myTextField.value;
if (myTextField.value == "")
{
alert ("Please enter a name");
return false;
}
myTextField.value = "";
}
function find()
{
//If the name already exists you should get a warning
var status = true;
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
{
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
status = false;
break;
}
}
if(status==true)
{
a[a.length] = myTextField.value;
}
myTextField.value = "";
}
The code had a couple of errors, here's a working version: http://jsfiddle.net/sAq2m/2/
html:
<input type="text" id="myText" /><br>
<input type="button" onclick="add()" value="Add a name" />
<input type="button" onclick="listItems()" value="List the names" />
<input type="button" onclick="find()" value="Find" />
js:
var a = [];
function listItems()
{
var s = "";
for(var i = 0; i < a.length; i++)
s = s + a[i] + "\n";
alert(s);
return false;
}
function add()
{
// If the text box empty you ask the user to enter a name.
var myTextField = document.getElementById("myText");
var v = myTextField.value
if (!v){
v = prompt("You have not entered a name, please enter one.");
}
a.push(v);
console.log(a);
myTextField.value = "";
return false;
}
function find()
{
//If the name already exists you should get a warning
var myTextField = document.getElementById("myText");
for (var i = 0; i < a.length; i++)
if (a[i] == myTextField.value)
{
alert ("Sorry, the name " + a[i] + " already exists. Try again");
return;
}
}

Categories

Resources