Create div X number of time from input - javascript

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.

Related

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>

Adding div elements to an array on button click

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.

Multidimensional Array Not Updating (or is it...?)

I have the most peculiar issue I can't seem to solve without writing band-aid code.
FULL SOURCE:
http://sinsysonline.com/tictactoe_test.html
or Fiddle:
http://jsfiddle.net/JsXEP/
I am using a multidimensional array for the JS and a table for the HTML for data and display purposes.
So, our data will look something like this for JS:
var b = [ ["","",""], ["","",""], ["","",""] ];
The table will be a standard table with some CSS tweaks for our HTML:
<table id="board">
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</table>
So, here is the problem. The input works just fine, resetting the game appears to work fine, but let's make a use-case so I can demonstrate the problem.
If I utilize a grid size of 3 initially, then try to make a game with a grid size of 4 without refreshing the page, the data seems to display at the top right for my array that the code is working as intended.
However, when you console.log(b), it never actually updates b and anything after the first three rows in the table don't respond.
I'm given a console error of:
TypeError: b[row] is undefined
Why isn't b actually updating with the increased value, even though I define it as var b=[]; at the beginning of my click-handler for #go?
And why is my #alert box for debugging filling in the correct b value?
Scratches Head
Any help is appreciated...
HTML:
<div id="dashboard">
<p>How large is your grid? (3-10)</p>
<input type="text" id="size" size="1" />
<p>Which icon would you like?</p>
<select name="mydropdown" id="mark">
<option value="check">Check-Mark</option>
<option value="x">Traditonal X</option>
<option value="o">Traditional O</option>
</select>
<h3 id="title">Troubleshooting Console</h3>
<input type="button" id="go" value="Create Board / Reset" />
<p id="alert">Alerts Live Here</p>
</div>
<table id="board">
</table>
Javascript:
$("#go").click(function () {
var b=[],
s = parseInt($("#size").val()),
v = $("#mark").val();
if (s<3 || s>10) { alert("That is not a valid input. Please select 3-10"); return; }
$('#board tr').remove();
$('#alert').text("Your Turn!");
for (var i = 0; i < s; i++) {
var t = [];
var $tr = $('<tr />').data('index', i + 1);
for (var j = 0; j < s; j++) {
t[j] = "";
$('<td />').data('index', j + 1).appendTo($tr);
}
b.push(t);
$("#board").append($tr);
}
$("#board").on('click', 'td', function () {
var $td = $(this),
td = $td.data('index')-1,
row = $td.parent().data('index')-1;
b[row][td] = "X";
$td.removeClass().addClass(v);
$('#alert').text(b);
});
});
FULL SOURCE:
http://sinsysonline.com/tictactoe_test.html
or Fiddle:
http://jsfiddle.net/JsXEP/
The problem is because of the closure property and multiple definitions of on click function. Updated Fiddle
$("#board").on('click', 'td', function () {
var $td = $(this),
td = $td.data('index')-1,
row = $td.parent().data('index')-1;
b[row][td] = "X";
$td.removeClass().addClass(v);
$('#alert').text(b);
});
This function is registered every time user changes the settings and whenever it is defined, it captures the b. So, first time, lets say, b is [3][3] and the on click function is created with that. Next time, b is [4][4] and a new on click function is created (old one still exists, with b [3][3]). So both of them are fired now onwards. If I select anything outside 3 x 3, the old one fails. That's why you are facing this problem.
So, I just moved the definition of on click function, b and v outside and it works fine now.

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Categories

Resources