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/
Related
I have a form that i enter the number of element then the text then the type div or section
and i click create i should remove the older div or section and create the new one
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
The problem is that the div or section appear but than disappear quickly i'm checking if the field are empty and if the field element number > 0 than i create the element that should appear in the result div
how can i solve this problem
The problem with your code is that you aren't preventing the <form> from refreshing the page.
if (validElement === false || validText === false || validType === false) {
e.preventDefault();
}
You use the above if statement to prevent the <form>'s default behaviour, but you set all those variables to true after creating your elements.
validElement = true;
validText = true;
validType = true;
So your script basically creates the elements and then the form refreshes the page.
Moving e.preventDefault(); outside of its if block would fix your immediate problem.
I would personally call e.preventDefault(); regardless of whether the users put in valid data, as a page refresh seems unneccesary in either case.
As for how to clear your results div, here is an elaborate post describing several ways of doing it.
/*get the number of element the text and the type*/
let element = document.querySelector("[name='elements']");
let text = document.querySelector("[name='texts']");
let type = document.querySelector("[name='type']");
let result = document.querySelector(".results");
document.forms[0].onsubmit = function (e) {
let validElement = false;
let validText = false;
let validType = false;
document.querySelectorAll(".results .box").forEach((box) => box.remove());
if (element.value !== "" && text.value !== "" && type.value !== "" && element.value > 0) {
// Clear the Results Container
while (result.firstChild) {
result.removeChild(result.lastChild);
}
// Repopulate the Results Container
for (let i = 0; i < element.value; i++) {
myBox = document.createElement(type.value);
myBox.className = "box";
myBox.id = `id-${i+1}`;
myBox.title = "Element";
myText = document.createTextNode(text.value);
myBox.appendChild(myText);
result.appendChild(myBox);
}
validElement = true;
validText = true;
validType = true;
}
e.preventDefault();
};
<form action="">
<input type="number" name="elements" class="input" placeholder="Number Of Elements" />
<input type="text" name="texts" class="input" placeholder="Elements Text" />
<select name="type" class="input">
<option value="Div">Div</option>
<option value="Section">Section</option>
</select>
<input type="submit" name="create" value="Create" />
</form>
<div class="results"></div>
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>
I need Happy Birthday to display only after a user puts the right input in prompt (which is 30). I want it to be hidden by default.
The reason I am doing it this way is that I want to add some CSS animation to this h1 tag later.
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday"> Happy Birthday! </h2>
You need to add hidden attribute to element with id = "bday"
document.getElementById("bday").style.display = "none";
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
document.getElementById("bday").style.display = "block";
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday" hidden> Happy Birthday! </h2>
No need to complicate, you can do it with less markup and improved functionality:
function myFunction() {
var myTextbox = document.getElementById("response");
var Age = prompt("How old are you?");
if (Age == 30) {
myTextbox.innerHTML = "Happy Birthday!";
} else if (Age == null) { // addition, if clicked on cancel
myTextbox.innerHTML = "";
} else {
myTextbox.innerHTML = "Really?";
}
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="response"></h1>
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
I want to display all the resulting expressions under the Result and Entered button every time I hit "=". But I am stuck trying to figure it out. This is what I have so far. Any help would be much appreciated. Thank you.
<!DOCTYPE html>
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = ["document.getElementById('op1').value", "document.getElementById('operator').value", "document.getElementById('op2').value",
"=","document.getElementById('result').value"];
dispArr.toString();
document.getElementbyId("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>
The values for dispArr are in quotes so they're treated as strings. Remove the quotes, then you are using document.getElementbyId instead of document.getElementById on line 39 (under dispArr.toString();)
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = [document.getElementById('op1').value, document.getElementById('operator').value, document.getElementById('op2').value,
"=",document.getElementById('result').value];
dispArr.toString();
document.getElementById("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>