Having trouble with displaying an image through an array - javascript

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>

Related

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>

How to create a <ul> based on an array number

I am trying to make a GitHub profile searcher and what i'm trying to do is:
Get the user Avatar
Get the user Name
Get the user Repositories
I'm having troubles with the last one.
What i can't figure out is how to create a UL based in the user repos quantity.
What i have HTML:
<!DOCTYPE html>
<html>
<head>
<title>Github Profile Searcher</title>
<link rel="stylesheet" href="github-profile.css" />
</head>
<body>
<div id="username-input" class="username-input">
Username:
<input class="username-input-text" type="text" />
</div>
<div id="github-profile" class="github-profile">
<div class="github-profile-avatar">
<span class="github-profile-username">mmckalan</span>
</div>
<div class="github-profile-name">
Alan Mac Cormack
</div>
<div class="github-profile-location">
Napoli,NA
</div>
<div class="github-profile-stats">
<div class="github-profile-stat">
<i class="icon github-icon-repo" /></i>
<span id = "github-profile-repo-count" class="github-profile-repo-count">50</span>
</div>
<div class="github-profile-stat">
<i class="icon github-icon-gist" /></i>
<span class="github-profile-gist-count">12</span>
</div>
</div>
</div>
<script src="github-profile.js"></script>
</body>
JS:
var usernameInput = document.querySelector('#username-input .username-input-text');
var emptyUser = {
login: "",
name: "",
location: "",
public_repos: "",
public_gists: "",
avatar_url: "notfound.png"
};
usernameInput.addEventListener('change', function(event){
var ghReq = new XMLHttpRequest();
ghReq.addEventListener("load", updateProfileBadge);
ghReq.open("GET", "https://api.github.com/users/" + usernameInput.value);
ghReq.send();
});
function updateProfileBadge() {
var response = JSON.parse(this.reponseText);
if (response.message === "Not Found") {
updateDomWithUser(emptyUser);
} else {
updateDomWithUser(response);
}
}
function updateDomWithUser(user) {
var profile = document.getElementById('github-profile');
profile.querySelector('.github-profile-username').innerText = user.login;
profile.querySelector('.github-profile-name').innerText = user.name;
profile.querySelector('.github-profile-location').innerText = user.location;
profile.querySelector('.github-profile-repo-count').innerText =
user.public_repos;
profile.querySelector('.github-profile-gist-count').innerText =
user.public_gists;
profile.querySelector('.github-profile-avatar')
.style.backgroundImage = "url(" + user.avatar_url + ")";
}
updateDomWithUser(emptyUser);
var quantity = document.getElementById('github-profile-repo-count');
var ul = document.createElement("ul");
document.body.appendChild(ul);
What i'm trying to do is something like this:
The quantity of LI is based on the number given by user.public_repos
But it has to fit to the user repos quantity, so i don't know how to solve it.
Could u please give me a hand?
As far as I know, call to "https://api.github.com/users/NAME" would give you only the number of public respos, not names or stars. For that, you need to call "https://api.github.com/users/NAME/repos" - it may be chained after the first call.
Still, creating X list elements without data is quite easy:
var ul = document.createElement("ul");
document.body.appendChild(ul);
for (var i = 0; i < user.public_repos; i++) {
var li = document.createElement("li");
li.textContent = 'example text';
ul.appendChild(li)
}
Or, if you'll get the repos data itself, in form of array:
var ul = document.createElement("ul");
document.body.appendChild(ul);
repos.forEach((repo)=>{
var li = document.createElement("li");
li.textContent = repo.name;
ul.appendChild(li)
})
Another thing - it's better to write
public_repos: 0,
than empty string.
To create a list of repos, you just have to loop through the JSON data returned by /users/{my_user}/repos. In your case, you need two Ajax calls:
The first one gives you information about the user
The second one gives you information about the user repos
Here is a minimal working example with my repositories:
function get(endpoint, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
callback(data);
} else {
console.log(this.status, this.statusText);
}
}
};
req.open('GET', 'https://api.github.com' + endpoint, true);
req.send(null);
}
function handleUser(data) {
var html = '';
html += '<li>' + data.login + '</li>';
html += '<li>' + data.name + '</li>';
document.querySelector('#user > ul').innerHTML = html;
get('/users/Badacadabra/repos', handleUserRepos);
}
function handleUserRepos(data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<li>' + data[i].name + '</li>';
}
document.querySelector('#repos > ul').innerHTML = html;
}
get('/users/Badacadabra', handleUser);
<div id="user">
<ul></ul>
</div>
<hr>
<div id="repos">
<ul></ul>
</div>

How to show nearest div id for a given input number?

Let's say I have the following input field:
<input id="inputField" type="number" value="">
and some divs such as:
<div id="1000"></div>
<div id="1200"></div>
<div id="1500"></div>
<div id="1900"></div>
...
When the user enters a number in the input field, I want my code to go to the nearest div id to that number.
e.g: If user enters 1300 then show div with id = "1200".
What's the most efficient way to implement that in javascript considering there will be a large number of divs?
Right now I'm doing:
<script>
function myFunction()
{
var x = document.getElementById("inputField").value;
if(x >= 1750 && x <= 1900)
{
window.location.hash = '#1800';
}
}
</script>
One way is to wrap all your divs with number ids in another div if you can (and give it some id, say 'numbers'); this allows you to find all the divs in your javascript file.
Javascript:
// Get all the divs with numbers, if they are children of div, id="numbers"
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
// Append the integer of the id of every child to an array
array.push(parseInt(children[i].id));
}
// However you are getting your input number goes here
let number = 1300 // Replace
currentNumber = array[0]
for (const value of array){
if (Math.abs(number - value) < Math.abs(number - currentNumber)){
currentNumber = value;
}
}
// You say you want your code to go to the nearest div,
// I don't know what you mean by go to, but here is the div of the closest number
let target = document.getElementById(currentNumber.toString());
Let me know if there's more I can add to help.
Demo
function closestNum() {
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
array.push(parseInt(children[i].id));
}
let number = document.getElementById('inputnum').value;
currentNumber = array[0]
for (const value of array) {
if (Math.abs(number - value) < Math.abs(number - currentNumber)) {
currentNumber = value;
}
}
let target = document.getElementById(currentNumber.toString());
document.getElementById('target').innerHTML = target.innerHTML;
}
<div id="numbers">
<div id="1000">1000</div>
<div id="2000">2000</div>
<div id="3000">3000</div>
<div id="4000">4000</div>
<div id="5000">5000</div>
</div>
<br />
<input type="text" id="inputnum" placeholder="Input Number" onchange="closestNum()" />
<br />
<br /> Target:
<div id="target"></div>
With some optimization this shall be ok-
var element;
document.addEventListener("change",
function(evt){
if(element && element.classList){
element.classList.remove("selected", false);
element.classList.add("unselected", true);
}
var listOfDivs =
document.querySelectorAll(".unselected");
var val = evt.target.value;
var leastAbs=listOfDivs[0].id;
for(let anIndex=0, len=listOfDivs.length;anIndex<len;anIndex++){
if(Math.abs(listOfDivs[anIndex].id-val)<leastAbs){
leastAbs = Math.abs(listOfDivs[anIndex].id-val);
element = listOfDivs[anIndex];
}
}
element.classList.remove("unselected");
element.classList.add("selected");
});
.selected{
background-color:red;
}
.unselected{
background-color:yellow;
}
.unselected, .selected{
width:100%;
height:50px;
}
<input id="inputField" type="number" value="">
<div id="1000" class='unselected'>1</div>
<div id="1200" class='unselected'>2</div>
<div id="1500" class='unselected'>3</div>
<div id="1900" class='unselected'>4</div>
This may work for you. Loops through each div and compared it to your inputted ID. Tracks closest one, hides all divs, then displays the closest.
document.getElementById("inputField").addEventListener("change", function(){
var divs = document.getElementsByTagName("div");
var closestDiv = -1;
var inputId = document.getElementById("inputField").value;
for(var i=0; i<divs.length; i++)
{
if(Math.abs(inputId - closestDiv) > Math.abs(inputId - divs[i].id) || closestDiv == -1)
{
closestDiv = divs[i].id;
for (var x = 0; x < divs.length; x++) {
divs[x].style.display = 'none';
}
divs[i].style.display = "block";
}
}
});
See it Live: jsfiddle.net

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>

Javascript: Taking values from a textbox and adding it to the divs

So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/

Categories

Resources