write a loop into html div with JS - javascript

I don't understand why this code is not working, could you help me please ?
I want that when you click on the button, the "theloop" div get filled with yo 0 , yo 1 etc... till the number you inputed
<p>
enter how many time you want the loop to repeat
<input id="nloop">
</p>
</br>
<button onclick="displayLoop()">
Try it
</button>
<p id="theloop"></p>
<script>
var nloop = document.getElementById("nloop").value;
var theloop = document.getElementById("theloop")
function displayLoop () {
for (var i=0; i<nloop; i++) {
theloop.innerHTML = "yo" + i;
}
}
</script>

You have many Syntax error + code error
<p>enter how many time you want the loop to repeat <input id="nloop"></p> </br>
<button onclick="displayLoop()">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop")
function displayLoop(){
var nloop = document.getElementById("nloop").value;
theloop.innerHTML = '';
for (var i=0; i<nloop; i++){
theloop.innerHTML = theloop.innerHTML + "yo" + i+ "<br/>";
}
}
</script>
You need to get the value of nloop when you call the function or the value will be the value when the script is loading, so an empty value.
If you affect something to innerHtml it will erase the content of the innerHtml.
I added BR only for the style you can ignore that.

You missed few syntax checks that I have corrected:
<p>enter how many time you want the loop to repeat <input id="nloop" /></p>
</br>
<button onclick="displayLoop();">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop");
function displayLoop () {
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
theloop.innerHTML = "yo" + i;
}
}
</script>

<script>
function displayLoop()
{
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
document.getElementById("theloop").innerHTML += "yo" + i;
}
}
</script>
This is working fine now :)

Related

Using The Input Value Instead Of The First Statement Of A Loop In JavaScript

I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.

Add, remove input box using javascript

So what i am trying to do is to have
1.add function to add an input box
2.remove function to remove the last input box in the list
3.sort function to sort the list of input texts by alphabetic order
I think my add function is working, but i am running into problem when i am trying to remove the last input box or trying to sort it.
Any idea or suggestion would be very much appreciated. thanks
<form id="mainform" >
<button onclick="add()">add</button>
<button onclick="remove()">remove</button>
<button onclick="sort()">sort</button>
</form>
<script>
var i = 0;
var count =0;
function add() {
var x= document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("placeholder", "Name");
i += 1;
count=count+1;
document.body.appendChild(x);
}
function remove(){
i -= 1;
count=count-1;
}
function sort(){
var x;
x=count;
var strings=[]
var t;
var i=0;
t=x;
while(t!=0){
strings.push(document.forms["mainform"].elements[i].value);
t=t-1;
i=i+1}
strings=strings.sort()
var j=0;
var msg='';
while(x!=0){
var msg=msg+strings[j]+'\n';
document.forms["mainform"].elements[j].value=strings[j];
j=j+1;
x=x-1;}
}
</script>
Looks like your add function adds the inputs directly to the body, while your sort function is looking for elements in the form['mainform'] element.
Your remove function is just decrementing your iterator without actually affecting the form at all.
That would do the job:
<form id="mainform" >
<input type="button" value="add" onclick="add()"></input>
<input type="button" value="remove" onclick="remove()"></input>
<input type="button" value="sort" onclick="sort()"></input>
</form>
<script>
function add() {
var x= document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("placeholder", "Name");
x.setAttribute("class", "someInput");
document.body.appendChild(x);
}
function remove() {
var childs = document.body.getElementsByClassName("someInput");
if(childs.length > 0) {
document.body.removeChild(childs[childs.length - 1]);
}
}
function sort(){
var hash = {};
var childs = document.body.getElementsByClassName("someInput");
// Map each element to its value
for(var i = 0; i < childs.length; i++) {
var currentElement = childs[i];
hash[currentElement.value] = currentElement;
}
// Remove all added elements
for(var i = 0; i < childs.length; i++) {
var currentElement = childs[i];
document.body.removeChild(currentElement);
}
// Sort by map keys, and add all elements back sorted
Object.keys(hash).sort().forEach(function(v, i) {
document.body.appendChild(hash[v]);
});
}
</script>
Please note that I replaced the button elements with input elements in order to prevent the form from being submitted.
Also pay attention that I marked each inserted textbox with class named "someInput". That will make our life easier when we want to query and get all the inserted textboxes.

Converting form text in HTML into an array in JS

I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview

How do you create a table in jQuery using html user input?

I'm pretty junior, so I'm unsure on if I worded the question properly.
I'm looking to create a textbox in HTML where the user can input the amount of columns and rows for the table. From there I need to use Javascript/Jquery to create the table when the button is clicked.
So far I have been able to create the text boxes. I capture the inputed numbers into variables, and created two for loops.
It doesn't work... :/
<body>
Set Rows:<br>
<input type="text" id="setRows">
<br>
Set Columns:<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm()'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
</body>
function myForm()
{
var setRows = document.getElementById("setRows").value;
//document.getElementById("demo1").innerHTML = setRows;
var setColumns = document.getElementById("setColumns").value;
//document.getElementById("demo2").innerHTML = setColumns;
}
$(document).ready(function()
{
$("button").click(function()
{
$("<table></table>").insertAfter("p:last");
for (i = 0; i < setRows; i++)
{
$("<tr></tr>").appendTo("table");
}
for (i = 0; i < setColumns; i++)
{
$("<td>column</td>").appendTo("tr");
}
});
});
The main problem is that you're setting the variables setRows and setColumns in a different function from the one that uses them. You should do everything in one function -- either bind it with the onclick attribute or with $("button").click() -- rather than splitting it into separate functions.
I also think it would be clearer to use nested loops to make it more obvious that you're adding cells to each row. appendTo() will automatically clone the object being appended if there are multiple targets, but this is an obscure feature (I'm very experienced with jQuery and didn't know about it until now) that isn't so obvious. It will also make the code easier to extend if you need to put different values in each cell (e.g. filling them from an array of data, or initializing with something like "row I col J").
function myForm() {
var setRows = $("#setRows").val();
var setColumns = $("#setColumns").val();
var table = $("<table>").insertAfter("p:last");
for (var i = 0; i < setRows; i++) {
var row = $("<tr>");
for (var j = 0; j < setColumns; j++) {
$("<td>column</td>").appendTo(row);
}
table.append(row);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:<br>
<input type="text" id="setRows">
<br>
Set Columns:<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm()'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
jsBin demo
<button type='button'>Create Table</button>
It's quite slow to append elements inside a for loop,
instead create a HTML representation of your table, and append it only once you're done generating it:
$("button").click(function(){
var setRows = +$("#setRows").val(); // Value to Number using Unary +
var setColumns = +$("#setColumns").val();
// THE HTML STRING
var table = "<table>";
// OUTER FOR LOOP : ROWS
for (var i=0; i<setRows; i++){
// START THE TR
table += "<tr>";
// INNER FOR LOOP :: CELLS INSIDE THE TR
for (var j = 0; j < setColumns; j++) {
table += "<td>column</td>";
}
// CLOSE THE TR
table += "</tr>";
}
// CLOSE THE TABLE
table += "</table>";
// APPEND ONLY ONCE
$("p:last").after(table);
});
As you see above I've used a for loop inside another for loop cause:
<tr> <!-- OUTER FOR LOOP (rows) -->
<td>column</td><td>column</td> <!-- INNER FOR LOOP (cells) -->
</tr>
This would work:
$(document).ready(function(){
$("#myBtn").click(function(){
var setRows = $('#setRows').val(); // get your variables inside the click handler so they are available within the scope of your function
var setColumns = $('#setColumns').val();
var rows=[]; // create an array to hold the rows
for (var r = 0; r < setRows; r++){ // run a loop creating each row
var cols=[]; // create an array to hold the cells
for (var c = 0; c < setColumns; c++){// run a loop creating each cell
cols.push('<td>column</td>'); // push each cell into our array
}
rows.push('<tr>'+cols.join('')+'</tr>'); // join the cells array to create this row
}
$('<table>'+rows.join('')+'</table>').insertAfter("p:last"); // join all of the rows, wrap in a table tag, then add to page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:<br>
<input type="text" id="setRows" value="4"/>
<br>
Set Columns:<br>
<input type="text" id="setColumns" value="5"/>
<button type="button" id="myBtn" >Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
You have to use a nested loop (as others have suggested).
Also when creating elements using jQuery - you don't have to specify both opening and closing tags - $("<elem />") works nicely..
Snippet:
$(function () {
var go = $("#go");
var cols = $("#columns");
var rows = $("#rows")
go.click(function () {
var numRows = rows.val();
var numCols = cols.val();
var table = $("<table />");
var head = $("<thead />");
var row = $("<tr />");
// build header
var headRow = row.clone();
for (var i = 0; i < numCols; i++) {
var th = $("<th />");
th.append(i);
headRow.append(th);
}
table.append(headRow);
// build table
for (var j = 0; j < numRows; j++) {
var addRow = row.clone();
for (var k = 0; k < numCols; k++) {
var cell = $('<td />');
cell.css({"border":"solid 2px teal"});
cell.append("<p>R:" + j + " |C:" + k + "</p>");
addRow.append(cell);
}
table.append(addRow);
}
$('body').append(table);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Rows:</label>
<input id="rows" />
<label>Columns:</label>
<input id="columns" />
<button id="go">Go!</button>
Your variables are created in a function (setRows and setColumns), so they are not available outside of this function. Define them globally if you want the "myForm" function to remain (it's not needed though).
Check this quick example, keeping your code intact:
var setRows = 0;
var setColumns = 0;
function myForm() {
//setRows = document.getElementById("setRows").value;
setRows = $('#setRows').val();
//setColumns = document.getElementById("setColumns").value;
setColumns = $('#setColumns').val();
}
$(document).ready(function() {
$("button").click(function() {
$("<table></table>").insertAfter("p:last");
for (i = 0; i < setRows; i++) {
$("<tr></tr>").appendTo("table");
}
for (i = 0; i < setColumns; i++) {
$("<td>column</td>").appendTo("tr");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:
<br>
<input type="text" id="setRows">
<br>Set Columns:
<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm();'>Create Table</button>
<p id="demo1"></p>
<p id="demo2"></p>
A few pointers going forward:
You can skip the "myForm" function, and instead put your variables just inside the ready-function.
You're also binding "button" to two things: to run myForm and to create your table. Removing the myForm-function, like stated above, obviously means you can remove the "onclick" event. But even if you keep the function, the call to "myForm" would be better placed inside the ready-function.

Sum of form input in Javascript

I want the user to enter a number then when it is submitted, it is inserted into the array totalBags.
The user can then submit another number, when submitted the array elements are added together.
E.g. Input = 2
Press submit
Output = 2
New input = 3
Press submit
Output = 5
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitOrder()
{
var allBags = [];
var bags_text = document.getElementById("bags").value;
allBags.push(bags_text);
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i]; // here is the problem... i think
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
function resetOrder()
{
document.getElementById("container").innerHTML = "<p><label for=\"bags\">No. bags: </label><input type=\"text\" id=\"bags\" /></p><p><input type=\"button\" value=\"Subit order\" onClick=\"submitOrder()\"> <input type=\"reset\" value=\"Reset Form\" /></p>";
}
</script>
</head>
<body>
<form name="order_form" id="order_form">
<div id="container">
<label>Total bags: </label><input id="bags" type="text" ><br>
<input type="button" id="submitButton" value="Subit order" onClick="submitOrder()">
<input type="reset" value="Reset" class="reset" />
</div>
</form>
</html>
I should rewrite the program a bit. First, you can define global variables which won't be instantiated in the function. You are doing that, which resets the variables. Fe
function submitOrder()
{
var allBags = [];
// ...
}
It means that each time you're clicking on the button allBags is created as a new array. Then you add an value from the input element. The result is that you have always an array with one element. It's best to declare it outside the function. By this, you ensure that the variables are kept.
// general variables
var allBags = [];
var totalBags = 0;
function submitOrder()
{
// the result is a string. You have to cast it to an int to ensure that it's numeric
var bags_text = parseInt(document.getElementById("bags").value, 10);
// add result to allBags
allBags.push(bags_text);
// total bags
totalBags += bags_text;
// display the result
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
by leaving out the loop, you have an more performant program. But don't forget to clear the array and the totalBags variable to 0 if you're using the reset button.
function resetOrder()
{
document.getElementById("container").innerHTML = "...";
// reset variables
totalBags = 0;
allBags = [];
}
Try to use:
for (var i = 0; i < allBags.length; i++)
{
totalBags += parseInt(allBags[i],10);
}
Or use Number(allBags[i]) if you prefer that.
Your element allBags[i] is a string and + between strings and concatenting them.
Further study: What is the difference between parseInt(string) and Number(string) in JavaScript?
function submitOrder()
{
var allBags = parseInt(document.getElementById("bags").value.split(""),10);//Number can also used
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i];
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}

Categories