Add line break to HTML from Js loop - javascript

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>

\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Related

Form response blank

I have some google script that generates an initial form then gathers a number does a lookup and then is supposed to return a second form (getfamily function). The second form which is dynamically generated returns blank. I can see the formHTML variable with data in the logger, but it comes up blank in the browser. Any suggestions would be appreciated.
var ssID="xxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
function doGet() {
var html = HtmlService.createTemplateFromFile('index2').evaluate()
.setTitle('Lookup').setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html;
};
function getfamily(form){
Logger.log(form.familyid);
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML = "<!DOCTYPE html>";
formHTML +="Hello!";
formHTML += '<form id="students">';
var filteredRows = rows.filter(function(row){
var message="made it";
if (row[0] === form.familyid) {
Logger.log(row[2]);
formHTML+= '<input type="checkbox" name ="students value='+ row[1] + '">'+ row[2] + '<br>';
return row[2];
}
});
formHTML+='<input type="submit" value="CheckIn">';
formHTML+='</form>';
Logger.log(formHTML);
var output = HtmlService.createHtmlOutput(formHTML).setSandboxMode(HtmlService.SandboxMode.NATIVE);
return output;
};
Your input type="checkbox" line is hard to figure out what you want. I presume that you plan in insert this form into an already exist DOM so no need the worrying about other tags just stick it in whatever div you have prepared for it.
function getfamily(form){
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML='<form id="students">';
var message="made it";
rows.forEach(function(row){
if (row[0]==form.familyid) {
formHTTML=Utilities.formatString('<input type="checkbox" name="students" value="%s" /><br />',row[2]);//I presume that you want to change the name but I cant tell how you planned to do it.
}
});
formHTML+='<input type="button" value="CheckIn" onClick="proceesForm(this.parentNode);" />';
formHTML+='</form>';
return HtmlService.createHtmlOutput(formHTML);
};
You can use submit if you really must but I find using google.script.run to be a lot easier. We need to see more of what you're doing to provide a complete answer.

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)
};

add element with DOM model before paragraph

I want add new input text before paragraph. But it working opposite add after text.
What is wrong at this code?
I use document.getElementById("p1").insertBefore(node); with this aim, but without success. Why does this happen?
Code:
<html>
<head>
<title>Adding text to a page</title>
<script>
function addText() {
var sentence=document.form1.sentence.value;
var node=document.createTextNode(sentence + " ");
document.getElementById("p1").insertBefore(node);
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p id="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="addText();">
</form>
</body>
</html>
Question:
How to solve this issue?
The insertBefore method needs to be called on the parent node (in which you want to insert), just like appendChild:
var node=document.createTextNode(sentence + " ");
var p1 = document.getElementById("p1");
p1.parentNode.insertBefore(node, p1);
If you want to add sentences to the paragraph instead of before it (right into the <body>), you would use this:
p1.appendChild(node); // insert at the end
// or
p1.insertBefore(node, p1.firstChild); // insert at the beginning
You could
Grab the new sentence.
Grab the original content.
Put them both together in a variable.
Clear the element.
Slap it back in.
Like so:
var addText = function() {
var sentence = document.form1.sentence.value;
var node = document.createTextNode(sentence + " ");
var el = document.getElementById("p1");
var original = el.innerHTML;
var newPara = sentence + ". " + original;
el.innerHTML = "";
el.innerHTML = newPara;
}
jsFiddle
Mind you, this is alot of steps, but hey, a million ways to skin a cat.
Of course you could always shorten all of that code up there to this:
var addText = function() {
document.getElementById("p1").innerHTML = document.form1.sentence.value + ". " + document.getElementById("p1").innerHTML;
}
new jsFiddle

Populating anchor link from several textfields

I try to populate several textfields to become something like this Check
Below is my script that I modified from here but this script is only show inside textarea and how to show inside anchor link and generate something like Check.
<div id="textBoxContainer">
<input type="text" id="name" onkeyup="UpdateTextArea();" name="name" />
<input type="text" id="group" onkeyup="UpdateTextArea();" name="group" />
</div>
<textarea id="textAreaResult"></textarea>
Check
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + "&";
}
textAreaFinalResult.value = finalResult;
}
</script>
If you want to target an anchor tag instead of the textarea, then obviously you need to change that accordingly:
<a id="hrefResult" href="check.php">link</a>
Then in your updateTextArea function, you need to target the anchor's href rather than the textarea's value. There's several other optimizations that can be made in there also, such as making an array of name/value pairs and then doing a join on them so you don't end up with the trailing &, etc.
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var length = textboxes.length;
var target = document.getElementById("hrefResult");
var params = [];
var baseref = 'check.php';
for (var i = 0; i < length; i++) {
params.push(textboxes[i].id + "=" + textboxes[i].value);
}
target.href = baseref + '?' + params.join('&');
}
What the heck, here's a fiddle of the whole thing.
It would probably make sense to change the name of the function itself since there's no textarea involved anymore, but I leave that as something for you to do.

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