Does anyone know why this simple program doesn't work?
It's a program that creates a group of radio buttons with Javascript.
<html>
<head>
<script>
function onWriteRadio(Valuse,numButtons,RadioName){
for(i=0;i<numButtons;i++){
document.write("<input type='radio' name=" + RadioName + "value=" +Valuse[i]+"/>");
document.write("<br/>");
}
}
</script>
</head>
<body onload="onWriteRadio([red,green,blue],3,'color')>
</body>
</html>
use this:
onWriteRadio(['red','green','blue'],3,'color')
string the array values. Currently, you say [red,green,blue], that means the variable red, variable green, variable blue, BUT you don't define them anywhere, so your program is saying "hmm, i do not know what red is.".. so string em.
put array values in quotes
onWriteRadio(['red','green','blue'],3,'color')
you left some quotation marks.
function onWriteRadio(values, radioName){
for (var i = 0; i < values.length; i++) {
document.write("<input type='radio' name='" + radioName + "' value='" +values[i]+"' >"+values[i]+" </ input>");
document.write("<br/>");
}
}
<html>
<body onload="onWriteRadio(['red', 'green', 'blue'], 'color')">
</body>
</html>
document.write() writes HTML expressions or JavaScript code to a document, which replaes your earlier html content.
document.write() executed after the page has finished loading will overwrite the page, or write a new page.
document.write() is a bad practice
place array values in quotes
add closing double quote for onload
make one string containing all inputs code and then write it
Your code should look smthng like this:
<html>
<head>
<script>
function onWriteRadio(Valuse,numButtons,RadioName){
var s = '';
for(i=0;i<numButtons;i++){
s += "<input type='radio' name=" + RadioName + "value=" +Valuse[i]+"/>"
}
document.write(s);
}
</script>
</head>
<body onload="onWriteRadio(['red','green','blue'],3,'color')">
</body>
</html>
Related
I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst
...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.
You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.
I need to pass arguments to a Excel VBA code from JavaScript of HTA.
I can successfully call VBA function, but unable to pass string arguments correctly.
JavaScript function can pass different string arguments.
Below is code in simple and demo form.
Excel-VBA code
Sub subTest(strName As String)
MsgBox strName
End Sub
HTA code with Javascript
<!DOCTYPE html>
<html>
<head>
<title>HTA</title>
<hta:application
id="oHta"
applicationname="htaNavi"
border="1"
borderstyle = normal
contextmenu = "yes"
caption="Navigator"
sysmenu="yes"
WINDOWSTATE="maximize"
>
</head>
<body>
<input type="button" value="testing" onclick="funRun('testng string')" />
<input type="button" value="testing second" onclick="funRun('testng')" />
</body>
<script>
var objExl;
var objWb;
var objExl =new ActiveXObject("Excel.Application");
objExl.Visible = true;
var objWb = objExl.Workbooks;
var strpath = '\path\testing_excel_web.xls';
objWb.Open(strpath);
function funRun(strName)
{
alert(strName);
objWb.Application.Run('testing_excel_web.xls!subTest(strName)');
}
</script>
</html>
I can call subTest, but message box populates strName as string but not 'testing string' as text.
I'm thinking you want:
objWb.Application.Run('testing_excel_web.xls!subTest("' + strName + '")');
This way, the value of the variable strName is concatenated to the command you are attempting to run.
I know nothing about this calling of a VBA function, so I'm not sure if you need the " around the strName like I provided or not.
In addition, to be safe, in case your strName value contains ", you should use this:
objWb.Application.Run('testing_excel_web.xls!subTest("' + strName.replace(/"/g, "\"") + '")');
Hopefully with this, the value of strName could be
The word "testing" here
or
"Here's a quote"
and it will still work.
The point is that if the string contains ", the Javascript would/could fail. If it would absolutely never contain ", then forget about it. But I think it's needed since any " in the value of strName will break the passing of it as a parameter.
The following loop works:
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
But the following doesn't:
<html>
<body>
<script type="text/javascript">
var i=0;
var x="i=0;i<=5;i++"
for (x)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
I'd just like to create a simple variable.
Please bear with me as I'm a newbie in JavaScript and let me know what I'm missing.
Let me provide my sample Google gadget:
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Sample Gadget" />
<UserPref name="order"
display_name="Results Order"
default_value="i = 0; i <= 5; i++" datatype="enum">
<EnumValue value="i = 0; i <= 5; i++" display_value="Ascending"/>
<EnumValue value="i = 5; i >= 0; i--" display_value="Descending"/>
</UserPref>
<Content type="html"><![CDATA[
<script type="text/javascript">
var i=0;
for (__UP_order__)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
]]></Content>
</Module>
It doesn't work because of the tags <> (they're not supported), and that's why I tried to define a variable for the EnumValue value.
When you say var x="i=0;i<=5;i++" you are creating a text string. This is not interpreted by JavaScript as you are expecting.
There is a definite difference between statements and text strings. Even though it looks to the eye like the same thing, it looks to the interpreter like a text string, like "hello" or "sdflkjsdflkjsdflj". JavaScript is not expecting a text string as loop parameters, it is expecting the three loop control parameters/statements. If you want to have a loop which starts and ends at different points, do something like this...
var i=0;
var start=0; //you can change the start position by changing this
var end=5; //and you can change the end also
for (i=start;i<=end;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
In short: You're confusing code with data. "i=0;i<=5;i++" is data (a piece of text, a string). But when writing a for-loop you have to write initialization, condition and step as code - you cannot pass text that happens to look like the code you'd write there. (In fact, you don't want to - what should happen when the data isn't like valid code? Not to mention it's not needed - see El Ronnoco's)
Because x is a string and you cannot use for statement with a string inside.
If you need to change the upper bound of a for statement you can use a variable instead the fix number 5.
Before the button ("play") is clicked, the program handles keydown but after clicking the button which draws a table, thereafter keydown messages are not handled.
I want this to work in IE or Firefox.
<html>
<head>
<script type="text/javascript">
var matrix,xbody,ybody,dir,key;
function draw()
{
for(var i=0;i<xbody.length;i++)
{
matrix[xbody[i]*50+ybody[i]].bgColor="black";
}
alert("draw");
}
function init()
{
document.write("<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >");
for(var i=0;i<50;i++)
{
document.write("<tr>");
for( var j=0;j<50;j++)
document.write("<td></td>");
document.write("</tr>");
}
document.write("</table></div>");
matrix=mine.getElementsByTagName("td");
xbody=new Array();
ybody=new Array();
xbody[0]=ybody[0]=0;
draw();
alert("pop");
}
function keypress(e)
{
alert("aiyoooo");
if((e.keyCode==38)|| ((e.which)&&(e.which==38)))
key=0;
else if((e.keyCode==40)|| ((e.which)&&(e.which==40)))
key=1;
else if((e.keyCode==37)|| ((e.which)&&(e.which==37)))
key=2;
else if((e.keyCode==39)|| ((e.which)&&(e.which==39)))
key=3;
}
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
</body>
</html>
You may want to read this article: http://java-programming.suite101.com/article.cfm/javascript_documentwrite_tutorial
The document.write command must be
carried out during the loading of the
page. So, if it is attached to any
event that executes after the page has
loaded, then the whole page will be
replaced with the contents of the
document.write command.
Rather than using document.write, you might want to instead use getElementById and then put your HTML in the innerHTML property of the element that you want the text to be in.
That may require adding a new div to hold the new text.
Since the answer would be rather long just => look here
in short document.write is just not the right way to go.
use smth different like document.createElement or go for a nice'n'easy javascript framework like jquery.
there you could just
var html = "";
html += "<table id='mine' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
html += ...
$(html).appendTo("body");
hope this helps