innerHTML with For Loop in Javascript - javascript

this is my coding. in this coding i want to print table in innerHTML in paragraph tag.This is working but the problem is when i click submit button this result show only last value like this "10*10=100" but i want to run full loop which i define in code from 1 till 10. Please solve this issue.
<html>
<head>
<title>Table Program</title>
</head>
<body>
<input type="text" id="table" placeholder="Enter table"/>
<input type="button" value="Submit" onClick="table()"/>
<p id="demo"></p>
<!----------------------------------------------------------------------------------------------->
<script type="text/javascript">
function table()
{
var value = document.getElementById("table").value;
var demop = document.getElementById("demo");
var a;
for(a=1; a <= 10;++a)
{
demop.innerHTML=(value+"*"+ a +"="+ value*a);
}
}
</script>
</body>
</html>

Your for loop is overwriting the innerHTML of demop each time it is executing.
So when your for loop reaches last iteration a will be 10 and hence you only get the last value "10*10=100"
So you should append the result every time you iterate your for loop
just make it like this
demop.innerHTML += (value + "*" + a + "=" + (value*a) + "<br />");
So you will get your output on seperate lines.

When you call demop.innerHTML = something you overwrite it each time.
You should either:
Put the entire string in a temporary result variable and then give it to innerHTML
Concatenate the different results by doing
demop.innerHTML = demop.innerHTML + (value+"*"+ a +"="+ value*a);

Related

Getting a Value from an Input Box and Assign it in a Variable using Javascript

Hi I'm just new to Javascript and I am trying to assign a value to a variable coming from the input box then access that variable in a loop. I have tried using document.getElementbyID('inputboxID').value; and document.getElementbyName('inputboxName').value; but it didn't work.
Here's my code:
<script>
var count = 0;
$(function(){
$('p#add_field').click(function() {
var num = document.getElementById('enfonum').value;
while (count < num) {
count +=1;
$('#container').append(
'<strong>Enforcer #'+count+'</strong><br/>'
+'<input id="field_ '+count+'"name="field[]'+'"type="text"/><br/>');
}
});
});
}
</script>
Here's the code for the input box:
<input type="text" id="enfonum" name="enfotxt"/>
and here's the code for the link that will trigger the script to be executed:
<p id="add_field">< a href="#"><span>» Add Enforcer</span></a></p>
You have to get value of enfonum input at run-time, not storing it at num var during initial page loading.
Here is the working sample with correct code:
var count = 0;
var num = document.getElementById('enfonum');
$('p#add_field').click(function () {
while (count < num.value) {
count += 1;
$('#container').append('<p><strong>Enforcer #' + count + '</strong><br/>'
+ '<input id="field_' + count + '" name="field[]' + ' "type="text"/><br/></p>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="text" id="enfonum" name="enfotxt" /></p>
<p id="add_field"><span>» Add Enforcer</span></p>
<div id="container"></div>
The reason your code is not working, is simply that document.GetElementById does not exists, the correct syntax is document.getElementById.
Here's a jsfiddle with an example.
Good luck and good continuation,
Cheers !
Remove the extra } in the code, it will give you syntax error.
Tried it afterwards,the code works.
Syntax errors can break your javascript, it is wise to use plugins like firebug for firefox to fish out javascript errors.
Let me know if it works.

I'm trying to add "grades" to an array and it isn't going as planned

The idea for this is to enter a "grade" or a general number, check to make sure that it is a number, ad it to the grade array, and then for each number added create a list item containing an input which contains the entered number.
I have 2 functions. The first one called ,check(), assigns the input value to the userInput variable, then checks that the variable is a number. if it is then it calls the adTo() function which is supposed to push the userInput variable into the grade[] array then update the list. This however is not what happens. here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<Title>Ultimate Grader</title>
<style>
</style>
<script>
function check(){
var userInput = document.getElementById('grade').value;
if ( isNaN(userInput) || userInput === " ") {
alert("please enter a Number");
}else {
adTo(userInput);
};
}
function adTo(input) {
var grade = [];
grade.push(input);
for (i=0; i<=grade.length; i++){
document.getElementById("list").innerHTML = "<li><input type='number' value='" + grade[i] + "'/></li>";
};
};
</script>
</head>
<body>
<form>
<input type="text" id="grade" name="grade" placeholder="Grade">
<input type="button" id="add" name="add" value="Add" onclick="check()">
</form>
<ul id="list">
</ul>
</body>
</html>
any ideas?
Every time you call adTo(), you're creating a new, empty array. You need to define the variable outside the function, so it will retain its value between calls.
Also, your for() loop is replacing the innerHTML each time through the loop, it's not appending to it. Use += to append.
var grade = [];
function adTo(input) {
grade.push(input);
var list = document.getElementById('list');
list.innerHTML = ''; // Empty it
for (var i = 0; i < grade.length; i++) {
list.innerHTML += "<li><input type='number' value='" + grade[i] + "'/></li>";
}
}
DEMO
There isn't really much need for that loop, though. Since the list should already have the items from previous calls, all you really need to do is append the new one:
function adTo(input) {
grade.push(input);
document.getElementById('list').innerHTML += "<li><input type='number' value='" + input + "'/></li>";
}
DEMO

Displaying multiple html text box values in an ascending order [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

How to call on text from a textbox to set a variable in javascript

I have a bit of a predicament. I am trying to run a variable on a loop so that it can change the loop. Here is the code that I have at the present time.
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable"><P>
</FORM>
<script type="text/javascript">
document.getElementById("Variable").value = i;
var i=5;
for (i=0;i<=5;i++)
{
document.write(" " + i);
document.write("<br />");
}
</script>
I am trying to call upon the text in the textbox from the form in order to define var i. I would also like to point out that I am no master of HTML, and if you see that I have done this all wrong, feel free to tell me that it cannot be done.
I think you mean something like this:
var count = parseInt(document.getElementById("Variable").value, 10);
var i;
for (i = 0; i < count; ++i) {
// ...do something...
}
What that does:
Looks up the element by its ID (you already had that): document.getElementById("Variable').
Retrieves the value of its value property, which is a string.
Converts the string into an number via parseInt, using decimal (as opposed to octal or hexadecimal).
Loops from zero (inclusive) to that number (exclusive).
Note that you can't use document.write after the main parse (initial load) of the page, and you probably don't want to use the value from a form field before the main parse of the page is complete, so you probably won't be doing document.write here. You might set the innerHTML of an element, something like that.
Re my "...you can't use document.write after the main parse...": Technically, you can, but you'll completely replace the page rather than just adding to it.
Re my "...and you probably don't want to use the value from a form field before the main parse...is complete...": You can, though, as long as the form field is above the script in the page markup. I did literally mean you probably don't want to, presumably you want the user to enter some value first.
Update: Here's a more complete example, with a live copy to play with:
var element, value, count, i;
element = document.getElementById("Variable");
if (!element) {
display("Element 'Variable' not found.");
}
else {
value = element.value;
count = parseInt(value, 10);
if (isNaN(count)) {
display("'" + value + "' is not numeric");
}
else {
for (i = 0; i < count; ++i) {
display("Loop " + i);
}
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
Live copy, the display function is obviously a bit of a placeholder for whatever it is you actually want to do.
I did not understand your exact question. but I guess this is your solution :
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" id="Variable">
<input type="button" value="run" onclick="renderIt()" />
<P>
</FORM>
<script type="text/javascript">
function renderIt()
{
var max = parseInt(document.getElementById("Variable").value);
for (i=0;i<=max;i++)
{
document.write(" " + i);
document.write("<br />");
}
}
</script>

Categories

Resources