I'm trying to modernize an intranet site somebody has built in the past which at the moment is forced into compatibility mode for IE5 through group policy. There is this javascript which creates x ammount of file input boxes within a form. This works on compatibility mode up to IE9 but not higher. I don't really know javascript I was hoping someone could help me modernize it?
<SCRIPT LANGUAGE="JavaScript">
var i = 0, j = 0;
var t1 = new Array();
function createtext() {
var inputLoop = document.getElementById("Many");
var table1 = document.getElementById("field");
for (i = 0; i < inputLoop.value; i++)
{
t1[i] = document.createElement('input');
t1[i].type = 'file';
t1[i].name = 'Image' + i;
t1[i].value = "Hello";
t1[i].size = 20;
document.forms[0].appendChild(t1[i]);
}
}
</SCRIPT>
<input name="b1" type="button" onClick="createtext();" value="Add">
If I run it on higher than IE9 the 'Add' button does nothing
The code works even in modern browsers. Just remove t1[i].value = "Hello"; because you can't set a value to input field programmatically.
var i = 0,
j = 0;
var t1 = [];
function createtext() {
var inputLoop = document.getElementById("Many");
var table1 = document.getElementById("field");
if (inputLoop.value) {
for (i = 0; i < inputLoop.value; i++) {
t1[i] = document.createElement('input');
t1[i].type = 'file';
t1[i].name = 'Image' + i;
t1[i].size = 20;
document.forms[0].appendChild(t1[i]);
}
}
}
<input type="text" id="Many">
<input name="b1" type="button" onClick="createtext();" value="Add">
<form action=""></form>
Related
I'm a new self taught programmer working on my first homework assignment, so I apologize if my naming convention is off. This is the most bizarre thing. No matter how I request the input value, (hoping to pull a number) it always reads as undefined.
Everything works in my javascript function except pulling the input value. I have used forms in the past, and the variables appear to be referencing it fine; I have tried both document.formName.inputName.value, as well as document.getElementById ('input-id').value and it returns undefined. I have renamed my form and variables so many times to see if that was the issue and stI'll nothing. I have tried both input type text and number, and stI'll undefined.
Am I missing something due to how new I am? Please help. Links to github and jsfiddle below.
https://github.com/MissElle/calculator?files=1
https://jsfiddle.net/MissElle/qf7xL8gj/
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff', '#ffbfbf', '#ffd299', '#ffffff', '#000000'];
function calcData(element) {
if(typeof element === 'number') {
console.log(element);
subCount.push(element);
var starDiv = document.createElement('div');
starDiv.className = 'star';
var starHolder = document.getElementById('star-holder');
starHolder.appendChild(starDiv);
starDiv.style.background = 'radial-gradient(circle, ' + starColors[Math.floor(Math.random() * starColors.length)] + ', transparent, transparent)';
numCount.innerHTML = subCount.length;
for(var i in subCount) {
subSum += subCount[i];
numSum.innerHTML = subSum;
var subMean = subSum/subCount.length;
numMean.innerHTML = subMean;
}
}else {
numCount.innerHTML = 'Not a Number';
console.log(element);
}
subSum = 0;
event.preventDefault();
}
function clearData() {
subCount = [];
subSum = 0;
subMean = 0;
numSum.innerHTML = '';
numMean.innerHTML = '';
numCount.innerHTML = '';
var starHolder = document.getElementById('star-holder');
var starDiv = starHolder.getElementsByClassName('star');
while(starDiv.length > 0) {
starHolder.removeChild(starDiv[0]);
}
}
<form name="compute" onsubmit="calcData()" onReset="clearData()">
<p class="bold">Please enter a number</p>
<input type="number" name="calculate" id="calculation" step="any"><br>
<input type="submit" name="submit" value="star">
<input type="reset" value="nostar" name="clearForm">
<div class="row">
<div class="typevalue"><h4>Count:</h4><h4>Sum:</h4><h4>Mean:</h4></div>
<div class="numbervalue"><p id="count"></p><p id="sum"></p><p id="mean"></p></div>
</div>
</form>
Move your variable declarations inside your function like this:
function calcData(element) {
var dataInput = document.compute.calculate.value;
var element = Number(dataInput);
var numCount = document.getElementById('count');
var numSum = document.getElementById('sum');
var numMean = document.getElementById('mean');
var subCount = [];
var subSum = 0;
var starColors = ['#51fffc', '#ffff96', '#96ffc7', '#f8d8ff', '#d2bfff',
'#ffbfbf', '#ffd299', '#ffffff', '#000000'];
...
If you declare your dataInput outside the function you get no value because that JS code is run after the page loads (before your user types any number in your function).
You have to declare it inside your function that way you get the value of your input when the user clicks on the button.
var vehicleLineDD = document.getElementById("vehicleLineDD");
for (i = 0; i < arr.length; i++) {
vehicleLineOp.text = arr[i].code + ': ' + arr[i].desc;
vehicleLineOp.value = arr[i].code;
vehicleLineDD.add(vehicleLineOp, null);
}
Hi Friends, here I am attach my code where I have struck now.
Problem is vehicleLineDD is the dynamic drop down. Depends on another drop down I should load the values here.
It is working fine in IE8, but in IE11 all the values are coming properly except vehicleLineDD.add(vehicleLineOp, null);
is not adding the values, only last value alone added. Every time when change the first drop down here I can see only one option.
Could anyone help me to come out from the the problem. Thanks in advance.
You need to create a new option element for the vehicleLineOp variable(using code similar to vehicleLineOp = document.createElement("option");), otherwise you're just constantly updating the same option element with different text and value attributes (which is why only the last applied text and value are showing up).
var vehicleLineOp;
var vehicleLineDD = document.getElementById("vehicleLineDD");
for (i = 0; i < arr.length; i++) {
vehicleLineOp = document.createElement("option");
vehicleLineOp.text = arr[i].code + ': ' + arr[i].desc;
vehicleLineOp.value = arr[i].code;
vehicleLineDD.add(vehicleLineOp);
}
Edit: Here's a working example that should work in both IE11 and IE8:
function populate() {
var arr = document.getElementById("input").value.split("\n");
var vehicleLineOp;
var vehicleLineDD = document.getElementById("vehicleLineDD");
vehicleLineDD.innerHTML = "";
for (var i = 0; i < arr.length; i++) {
vehicleLineOp = document.createElement("option");
vehicleLineOp.text = arr[i];
vehicleLineOp.value = arr[i];
vehicleLineDD.add(vehicleLineOp);
}
}
var btn = document.getElementById("btnPopulate");
if (btn.addEventListener) {
btn.addEventListener("click", populate);
} else {
btn.attachEvent("onclick", populate);
}
Add each choice as a new line in the text area below, thn click "Populate Dropdown":<br/>
<textarea id="input" style="vertical-align:top;height:4em;">Example 1
Example 2
Example 3</textarea>
<input type="button" value="Populate Dropdown" id="btnPopulate" />
<br/>
<select id="vehicleLineDD"></select>
I have made a simple dynamic form to generate input boxes.
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+"/>
<input type="button" onclick="removeSelect();" value="-"/>
<input type="button" onclick="xmlData();" value="XML" />
</div>
<div id="main">
</div>
</body>
Here's the javascript code:
(function () {
var selele=0;
var brindex=0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
var textbox = document.createElement('input');
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "           ";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
});
I can't get it to work on jsFiddle, the buttons don't work.
They work fine if I embed it in a tag.
Can anybody help me fix them.
EDIT: I guess i added anonymously because I wanted the var selele and brindex globally for all these functions.
I have made the code changes.
JSFIDDLE
Your functions are within an anonymous function and thus not available from outside.
First remove the code from the anonymous function (see here: http://jsfiddle.net/uH84W/6/), then fix the console errors you get (I assume that's not the whole code).
function addSelectBox() {...
In your fiddle you select onload but you change onload to no warp-in or no warp-in now it's work fine
I need help with below code.
What I need to do is to pass the URL parameters to these two hidden fields.
http://www.yoursite.com/index.php?fieldOne=Work&fieldTwo=Play
It doesn't seem to be working. Also I cannot add id to the form field.
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
<script>
function FillForm() {
var FormName = "myformname";
var qLoc = location.href.indexOf('?');
if(qLoc < 0) { return; }
var q = location.href.substr(qLoc + 1);
var list = q.split('&');
for(var i = 0; i < list.length; i++) {
var kv = list[i].split('=');
if(! eval('document.'+FormName+'.'+kv[0])) { continue; }
kv[1] = unescape(kv[1]);
if(kv[1].indexOf('"') > -1) {
var re = /"/g;
kv[1] = kv[1].replace(re,'\\"');
}
eval('document.'+FormName+'.'+kv[0]+'.value="'+kv[1]+'"');
}
}
FillForm();
</script>`
NULL had it kind of there with the simplification (albiet there is a small error in your code regarding the iteration over the query). Here is NULL's simplification corrected, and also my guess as to why you're not getting the desired results:
<form name="myformname">
<input type="hidden" name="fieldOne">
<input type="hidden" name="fieldTwo">
</form>
<script type="text/javascript">
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query[i].split("=");
//alert(split);
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
</script>
1) Make sure you're using a form tag with an id. I can't see your HTML.
2) Be sure that you are not seeing new data appear in the hidden <input>'s? I advise using a debugger and checking the live DOM tree as opposed to the source code. Some debuggers don't update the source in real-time.
EDIT:
Based on new information from the questioning party, here is another stab at a fix:
<script type="text/javascript">
$(document).ready(function(){
var formName = "dSOfferAllE10Test-1349977611926";
var query = location.href.split("?").pop().split("&");
var len = query.length;
var split, elem;
for (var i = 0; i < len; i++ ) {
split = query[i].split("=");
$('form[name="'+formName+'"]').find('input[name="'+split[0]+'"]').each(function(){
$(this).val(split[1].replace(/"/g, '\\"'));
});
}
});
</script>
This uses jQuery, so make sure that you attach a reference to jQuery in your <head> (or at least near the top of the <body> if you don't have access to the <head>. Best to grab the snippet from the Google-hosted version: https://developers.google.com/speed/libraries/devguide#jquery
You can simplify your code:
var formName = "myformname",
query = location.href.split("?").pop().split("&"),
i = 0,
len = query.length,
split, elem;
for ( ; i < len; i++ ) {
split = query.split("=");
elem = document[formName][split[0]];
if ( elem ) {
elem.value = split[1].replace(/"/g, '\\"');
}
}
I’m trying to call a user input array.
I’m very new on Javascript but know I somehow need to reference the array (it is somewhere where I put the ???).
<script>
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var planetIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[planetIndex][0]=val1;
planetIndex++;
document.getElementById('name').value = ''; };
function worldChange() {
var newplanet = ????????????
var whichWorld = Math.floor(Math.random()*newplanet.length);
return planetIndex[whichWorld];
var planets = document.getElementsByClassName("world-name")
for (var i=0; i < planets.length; i++) {
planets[i].innerHTML = worldChange();};
};
</script>
<body>
<div>
<form>
<input type="integer" id="name"/>
<input type="button" value="Add Planets" onclick="insert (this.form.name.value);"/>
</form>
<input type="button" value="See planet!" onClick="worldChange()" />
<br> Hello <span class="world-name">Earth!</span><br />
</div>
</body>
I got both elements of the script to work perfectly on my site so every time someone hits a button it changes the guy in the story. But as you see if pulls from the array I created. I want to pull from an array that a user creates so they could input their own list of names.
so this script works fine:
function newGuy() {
var guys = new Array ("Jeff", "Mike", "George", "Harold");
var whichGuy = Math.floor(Math.random()*guys.length);
return guys[whichGuy];}
var guy = document.getElementsByClassName("guy")
for (var i=0; i < guy.length; i++) {
guy[i].innerHTML = newGuy();}
And this script works alone:
var arrayX =5;
var arrayY =1;
var array=new Array(arrayX);
var guyIndex=0;
for (x=0; x<array.length; x++)
{array [x] = new Array(arrayY);}
function insert(val1){
array[guyIndex][0]=val1;
guyIndex++;
document.getElementById('name').value = ''; };
Just baffled on how to put them together.
There are a lot of problems with your script but to give you an idea on how to get it to work :
var planets = [];
// define how many planets there will be initially
var initialLength = 5;
// add the initital planets
for (x = 0; x < initialLength; x++) {
planets.push("planet" + x);
}
function insert() {
var planetToInsert = document.getElementById('name').value;
if (planetToInsert) {
// add the input to the array of planets
planets.push(planetToInsert);
document.getElementById('name').value = '';
} else {
alert("please enter a value");
}
}
function worldChange() {
// randomly pick an index
var whichWorld = Math.floor(Math.random() * planets.length);
document.getElementById('world-name').innerHTML = planets[whichWorld];
}
working sample here
For finding problems in you code jsFiddle can be of excellent help. Run JSlint to find the basic errors, put in alerts as poor mans debugging.
For a good javascript book I would recommend javascript patterns