Adding div elements to an array on button click - javascript

The page I am working on contains a div element with the id "exam", a button with the id of "copy" and a second button with the id "array". The div element contains the text "Exam 1" and when the "copy" button is clicked, this div is duplicated each time the button is clicked. The "array" button is supposed to add each of these "exam" divs to an array and use the alert function to display the length of the array. I can't figure out how to go about having these div elements added to an array when the button is clicked.
Here is the HTML I have so far (this also includes Javascript and CSS):
<html>
<head>
<title>Exam 1 Tanner Taylor</title>
<style type="text/css">
#exam {
border: 2px double black;
}
</style>
</head>
<body>
<div id="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()" >
<input type="button" id="array" value="Get Array" onclick="makeArray()">
</body>
<script type = "text/javascript">
var TTi = 0;
var TToriginal = document.getElementById("exam");
function copy() {
var TTclone = TToriginal.cloneNode(true);
TTclone.id = "exam";
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam[];
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
}
}
</script>
</html>
There's more to it, but I removed the parts that didn't actually deal with this problem. As you can see, I've started the makeArray() function, but wasn't really sure where to go from there, I feel like this is the function I need the most help with. Any suggestions?

I would add a class name to the exam div and use getElementsByClassName() to get all the divs with that class.
HTML:
<body>
<div id="exam" class="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="makeCopy()" />
<input type="button" id="array" value="Get Array" onclick="makeArray()" />
</body>
JS:
var TTi = 0;
var TToriginal = document.getElementById("exam");
function makeCopy() {
console.log('copy');
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam = document.getElementsByClassName("exam");
alert(TTexam.length);
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
console.log(TTexam[TTindex]);
}
}
You can replace the alert() and console.log() with whatever business logic you want.
Check out a working fiddle at http://jsfiddle.net/JohnnyEstilles/w6fdm5th/.

Some suggestions and something you maybe can proceed from: First, id-attributes should be unique, so it'd be better to use classnames:
<div class="exam">Exam 1</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()">
<input type="button" id="array" value="Get Array" onclick="makeArray()">
For the script:
var TTexam = [];
function copy() {
var TToriginal = document.getElementsByClassName("exam")[0];
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
alert(TTexam.length);
for (var TTindex = 0; TTindex < document.getElementsByClassName("exam").length; TTindex++)
{
TTexam.push(document.getElementsByClassName("exam")[TTindex]);
}
alert(TTexam.length);
}
That's just for starters. TTexam is an array defined global, just in case it should be accessible for both functions. But question is really what exactly you want to do - if you want to generate the array only once when you finished adding divs or if it should be possible to generate a new array containing all divs each time you click 'Get Array'. Then the array should be defined in the makeArray()-function.
To avoid having the same divs as doubles in the array in case of global definition, it would e.g. be possible to add a data-attribute with a counter to each newly created div and, when creating the array a second time, only add the new ones. Or it would be possible to add each new div to the array when it's added using TTexam.push(TTclone); in the copy()-function.

Related

how to i get access to my remove button using javascript [duplicate]

I have a page with anchor tags throughout the body like this:
<a id="test" name="Name 1"></a>
<a id="test" name="Name 2"></a>
<a id="test" name="Name 3"></a>
The ID is always the same but the name changes.
I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I've got to so far:
document.write(document.getElementById("readme").name);
This writes out the name of the first anchor tag. I'm in need of a way to get multiple elements by Id.
Any help is greatly appreciated.
If you can change the markup, you might want to use class instead.
HTML
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>
JS
var elements = document.getElementsByClassName("test");
var names = '';
for(var i = 0; i < elements.length; i++) {
names += elements[i].name;
}
document.write(names);
jsfiddle demo
Today you can select elements with the same id attribute this way:
document.querySelectorAll('[id=test]');
Or this way with jQuery:
$('[id=test]');
CSS selector #test { ... } should work also for all elements with id = "test". Вut the only thing: document.querySelectorAll('#test') (or $('#test') ) - will return only a first element with this id.
Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .
For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).
As oppose to what others might say, using the same Id for multiple elements will not stop the page from being loaded, but when trying to select an element by Id, the only element returned is the first element with the id specified. Not to mention using the same id is not even valid HTML.
That being so, never use duplicate id attributes. If you are thinking you need to, then you are looking for class instead. For example:
<div id="div1" class="mydiv">Content here</div>
<div id="div2" class="mydiv">Content here</div>
<div id="div3" class="mydiv">Content here</div>
Notice how each given element has a different id, but the same class. As oppose to what you did above, this is legal HTML syntax. Any CSS styles you use for '.mydiv' (the dot means class) will correctly work for each individual element with the same class.
With a little help from Snipplr, you may use this to get every element by specifiying a certain class name:
function getAllByClass(classname, node) {
if (!document.getElementsByClassName) {
if (!node) {
node = document.body;
}
var a = [],
re = new RegExp('\\b' + classname + '\\b'),
els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++) {
if (re.test(els[i].className)) {
a.push(els[i]);
}
}
} else {
return document.getElementsByClassName(classname);
}
return a;
}
The above script will return an Array, so make sure you adjust properly for that.
Here is a function I came up with
function getElementsById(elementID){
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++){
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.
However, I have come to discover that dollar sign function has become
the more-or-less de facto shortcut to document.getElementById(). Let’s
face it, we all use document.getElementById() a lot. Not only does it
take time to type, but it adds bytes to your code as well.
here is the function from prototype:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
[Source]
You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.
You should use querySelectorAll, this writes every occurrence in an array and it allows you to use forEach to get individual element.
document.querySelectorAll('[id=test]').forEach(element=>
document.write(element);
});
More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.
If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.
One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.
If IDs are for identification, why must it be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.
I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.
If you want a solution that actually finds all IDs of the same name though, then it's this:
function getElementsById(id) {
const elementsWithId = []
const allElements = document.getElementsByTagName('*')
for(let key in allElements) {
if(allElements.hasOwnProperty(key)) {
const element = allElements[key]
if(element.id === id) {
elementsWithId.push(element)
}
}
}
return elementsWithId
}
EDIT, ES6 FTW:
function getElementsById(id) {
return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}
With querySelectorAll you can select the elements you want without the same id using css selector:
var elems = document.querySelectorAll("#id1, #id1, #id3");
You can get the multiple element by id by identifying what element it is. For example
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
$("div#id")
. This will get you array of elements you loop them based on your logic.
No duplicate ids, it's the basis. If you have an html structure as
<a id="test1" name="Name_1">a1</a>
<a id="test2" name="Name_2">a2</a>
<a id="test3" name="Name_3">a3</a>
Nowadays, with ES6, you can select multiple elements with different id's using the map() method:
const elements = ['test1', 'test2', 'test3'].map(id => document.getElementById(id));
console.log(elements);
// (3) [a#test1, a#test2, a#test3]
Of course, it's easier to select them if they have a same class.
The elements with the different ids are in an array.
You can, for example, remove them from the DOM with the forEach() method:
elements.forEach(el => el.remove());
An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".
Below is the work around to submit Multi values, in case of converting the application from ASP to PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
var Arr_Elements = [];
Arr_Elements = document.getElementsByClassName("MultiElements");
for(var i=0; i<Arr_Elements.length; i++) {
Arr_Elements[i].value = '';
var Element_Name = Arr_Elements[i].name;
var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
var Multi_Elements = [];
Multi_Elements = document.getElementsByName(Element_Name);
var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
if (Main_Element_Type == "CheckBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements[j].checked == true) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
if (Multi_Elements[j].value != '') {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
Arr_Elements[i].value = Multi_Elements_Values;
}
}
</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
<table>
<tr>
<td>Check Box</td>
<td>
<input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
</td>
<td>
<input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
<input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
<input type="hidden" name="SdPart" id="SdPart" value="3451"></input>
<input type="textbox" name="Test11" id="Test11" value="345111"></input>
<!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc
-->
<input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
</td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
testCB.php
<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>
Use jquery multiple selector.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>multiple demo</title>
<style>
div,span,p {
width: 126px;
height: 60px;
float:left;
padding: 3px;
margin: 2px;
background-color: #EEEEEE;
font-size:14px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
<script>$("div,span,p.myClass").css("border","3px solid red");</script>
</body>
</html>
Link : http://api.jquery.com/multiple-selector/
selector should like this : $("#id1,#id2,#id3")

Search for contents of element and click its parent

I am trying to create an extention which clicks on an item of the price given by the user. Here is the relevant popup.html:
<input style="display:none" /><input type="text" id="userInput" value='' />
<button id="clickme">Run</button>
When 'clickme' is clicked, it runs this popup.js:
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+ document.getElementById("userInput").value+".00";
alert(price);
$("p:contains("price")").parentNode.click();
});
If you type the desired price in in the form as 48, it returns an alert with the value $48.00.
It then shuold click on the item of that price, however this currently isn't working. Here is the code of the relevant part of the website which I am trying to run my extention on (not my website):
<div class="grid__item wide--one-fifth large--one-quarter medium-down--one-half">
<a href="/collections/1seventeenweek7/products/copy-of-supreme-dazzle-warm- up-top-red" class="grid-link text-center">
<p class="grid-link__title">Supreme Corner Cap Light Blue</p>
<p class="grid-link__meta">
<span class="visually-hidden">Regular price</span>
$48.00
</p>
</a>
</div>
I am trying to get it to search for the p element containing $48.00, and then click on the a element which is the parent element, but this is not currently working. What am I doing wrong? - thanks
Here you go. This will work!
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
alert(price)
for (let i = 0; i < metas.length; i++) {
if (metas[i].innerHTML.includes(price)) metas[i].parentNode.click()
break
}
})
Personally, I'd really like to use something like the following, yet I forgot that getElementsByClassName doesn't return an array, but rather a NodeList object.
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
var match = metas.find((curr) => curr.innerHTML.includes(price))
match.parentNode.click()

How do I store the string value from input field in an empty array?

I'm having trouble storing input values from <input> tag in HTML into array of strings, I can't figure out how am I suppose to do that. I have an idea on how that might look like, however I still can't get it to work.
I believe that I have to use .push() and .join() method and += or + operator, it's just I do not know where to put them.
The first thing I did was searching on Google How to store string value from input in an array of strings? but I only found on how to do it using <form> tag in HTML and I can't do that. I can't use the <form> tag.
Here's the code that I think should look like
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
var inputName = document.getElementById("input");
var cityArray = [""];
// This triggers immediately when the browser loads
window.onload = (
// Pickup the string from input and add it on the previously created array
function submit() {
inputName.value;
for (var i = 0; i < array.length; i++) {
array[i];
}
}
);
I also need a piece of code that will delete the value that was typed in a <input> field right after the Submit button is pressed, so that the user doesn't need to press Backspace in order to type the second input value.
Here is a working code snippet.
When you click the submit button, that will call the submit() function. Since your array is defined to be global, you can access it within the function. You do not need to iterate over the array, and you can simply use the .push() method to easily append a string to your array.
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
Hope this helps!
Yes you need to use .push() method it will add the new entered string to the array, without the need to iterate it:
function submit() {
cityArray.push(inputName.value);
}
And you need to initialize your array as an empty array with [] :
var cityArray = [];
And you don't need to create the submit function in the body.onload event handler because it won't be accessible outside of it and may lead for an error.
Demo:
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
Js Code
//declare your array like this
var yourArray = new Array();
//To add items to array:
yourArray.push(yourString);
//To get you can use indexing like(almost any other language)
yourArray[i]
//You can even set as an object array like this:
yourArray.push({
text: 'blablabla'
})
//So, in your case, filling up the array could be something like this:
var inputText = document.getElementById('input').value;
yourArray.push(inputText);
// show it
for (var i = 0; i < yourArray.length; i++) {
alert(yourArray[i]);
}
HTML Script
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>

Javascript will not pass information into function from html

Ok so very new to Javascript. Trying to learn the code by simply changing the text on a button using an external javascript file. But I can't even get javascript to read the buttons valueexternally, in Chrome's debug tools I see my button value is btn="". It reads the button object but can't read its properties.
<html>
<head>
<title> Test </title>
<script type="text/javascript" src="Gle.js"></script>
</head>
<body>
<div><canvas id="Gle" width="800" height="600"></canvas>
</div>
<div>
<h2>Enter the mass and coordinates</h2>
<input id="txtbox" type="text" /><br/>
<button id="btn" onclick="change()">Add</button>
</div>
</body>
</html>
The Gle.js
"use strict";
function change() {
var x = document.getElementById("btn").value;
var elem = document.getElementById("btn");
var txt = document.getElementById("txtbox");
txt.text = elem.value;
elem.value = "Ok";
}
When I debug the x value it is "", nothing changes on my screen. I am using brackets IDE.
x is empty because '#btn' doesn't have the 'value' attribute specified. The "Add" string is inside its inner HTML (or text),
alert(document.getElementById("btn").innerText);
And you can index this in the event scope, it's a reference of '#btn', this.innerText.
A alternative is to get the '#btn' child nodes values, which is cross-browser.
alert(this.childNodes[0].nodeValue);
This alert the first text specified in the element inner.
I'm expecting to have the button title "Add" appear?
The button doesn't have a value attribute so its value property is an empty string.
"Add" is the content of the text node inside the button element.
var x = document.getElementById("btn").firstChild.data;
You can try by assigning value attribute to your button
<button id="btn" onclick="change()" value="Add">Add</button>
If you want to update the text of a button based on what's in the input box the code could look like this:
<button id="myButton">Change Me</button>
<input id="myInput" type="text" value="To This"/>
and in the JS:
document.getElementById("myButton").click(function(){
var inputValue = document.getElementById("myInput").value
document.getElementById("myButton").innerText = inputValue
// You could also use 'this' to refer to document.getElementById("myButton"):
// this.innerText = inputValue
})

Create div X number of time from input

I am trying to create div using javascript and jquery.
My Code so far:
<script>
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
var newDiv = $('#server div:first').clone();
$('#server').append(newDiv);
}
</script>
<input type="text" name="numserver"><br>
<button onclick="new_server()">GO</button>
<br>
<div id="server">
<div id="1">
<table border="3"><tbody>
<tr><th colspan="4" style="background-color:#b0c4de;">Server 1</th></tr>
<br>
<tr><td>Technology<select name="tech[]"><option value="w">Web</option><option value="d">DB</option><option value="m">Mail</option><option value="o">Other</option></select><br>
<br></td>
<td>CPU? <input type="text" name="cpu[]"><br></td>
<td>Memory? <input type="text" name="memory[]"><br></td>
<td>Disk Space? <input type="text" name="space[]"><br></td></tr>
<br>
</tbody></table>
</div>
</div>
My end result is for the user to be able to enter the amount of servers and click GO and then the divs are automatically created.
I know how to get the numOfWindows value but i think it should work with a static value for now.
The code is correct, but how says adeneo, you don't have a DOM ready handler.
Use instead something like this:
function LoadMyJs(){
var numOfWindows = 3;
var arrayDiv = new Array();
for (var i = 0; i < numOfWindows; i++)
{
var newDiv = $('#server div:first').clone();
$('#server').append(newDiv);
}
}
<body onLoad="LoadMyJs()">
You are trying to run the script which works with undefined HTML. To solve this you can either move your script after defining HTML or use jquery shortcut document.ready function such as $(function(){<your code here>});.
In first case event handler has to be a global variable right away. Otherwise you declare this variable before shortcut scope.
Next you define that event handler function obtains input value ($('input[name="numserver"]').val()). And now you can generate as many divs as defined by the value(Array.apply(null, [+value]).map(function(){<generator here>})). To generate copies clone method may be used and generated divs should be inserted into div container as you do.
Looks like you're trying to generate divs by "GO" button click. In your case to do that event handler function should be named "new_server". And you don't call this function in "onclick" attribute you just declare it.

Categories

Resources