I am refactoring old code and am unable to find a solution to the typeerror (I understand the use of eval is frowned upon but in my case there is no need for security).
I have objects like:
var Ansys = {key:'ansyskeys', loaded:0, display: "none", otherkey: 'anotherkey'};
var Cadence = {key:"cdskeys", loaded:0, display: "none", otherkey: 'cotherkey'};
I had previous HTML code that was static that I am trying to refactor to be dynamic:
<div id="ansyskeys" style="display:none">
<select id="anotherkey" size="5" onchange="selectOther('anotherkey')"></select>
</div>
Which is called from (vendor holds the name of my object I want):
document.getElementById(eval(vendor).key).style.display = eval(vendor).display;
How would I go about changing the HTML to be something like (I am using display in my object for something else)
<div id="eval(vendor).key" style="display:none">
<select id="eval(vendor).otherkey" size="5" onchange="selectOther(eval(vendor).otherkey)"></select>
</div>
Any help will be much appreciated.
If vendor holds the object you need:
var key = vendor.key;
var otherkey = vendor.otherkey;
var myDiv = document.createElement('div');
var html = '<select id="' + otherkey + '" size="5" onchange="selectOther('+ otherkey + ')"></select>';
myDiv.innerHTML = html;
myDiv.id = key;
document.body.appendChild(myDiv);
Related
I am trying to refactor old code without completely redoing the program.
I have objects that are strategically named to be a value of the string from vendor. (vendor = "Ansys" or vendor = "Cadence")
var Ansys = {key:'ansyskeys', loaded:0, display: "none", otherkey: 'anotherkey'};
var Cadence = {key:"cdskeys", loaded:0, display: "none", otherkey: 'cotherkey'};
My previous HTML code that was static and had many entries that looked like:
<div id="ansyskeys" style="display:none">
<select id="anotherkey" size="5" onchange="selectOther('anotherkey')"></select>
</div>
To replace this, I made a function -ignore the use of eval, security is no concern:
function createDiv()
{
var vendorKey = eval(vendor).key;
var otherVendorKey = eval(vendor).otherkey;
var myDiv = document.createElement('div');
var html = '<select id="' + otherVendorKey + '" size="4" onchange="selectOther('+ otherVendorKey + ')"></select>';
myDiv.innerHTML = html;
myDiv.id = vendorKey;
document.body.appendChild(myDiv);
}
I am recieving my desired result, however, when I try to use selectedIndex in the function selectOther, it appears that mk is null.
function selectOther(wid)
{
var mk = document.getElementById(wid);
alert(mk);
var index = mk.selectedIndex;
key = mk.options[index].value;
setKey ();
getKeyStats ();
}
The HTML seems to be working, but doesnt seem to recognize the id from wid. Any help would be much appreciated.
I am new to JavaScript. What I am trying to do is make a div and inside of it there will be another div. Within my script code I am trying to create new instances of that div using factory function if that is the right name for it, and then change the innerHTML of the child div if that is possible. Thanks in advance.
<div class = "loopBlock" style="width:350px;">
<fieldset>
<legend style="color:black;font-weight:bold;">While Loop</legend>
<table>
<tr>
<td>Condition:</td>
<td><input type="text" /></td>
</tr>
</table>
<div class = "codeDivClass" id = "codeDiv">
HelloWorld!
</div>
</fieldset>
</div>
<script>
var loopDiv = document.getElementsByClassName("loopBlock");
var loopi =1;
function loopObject(){
var loopDivObject = document.createElement("div");
loopDivObject.innerHTML = loopDiv[0].innerHTML;
loopDivObject.className = "loopBlock";
loopDivObject.id = "loopBlock"+loopi;
loopi++;
return loopDivObject;
};
var functionCodeDiv = document.getElementById("codeDiv");
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
var id = "loopBlock"+i+1;
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
}
</script>
Didn't really get how it should work, but I'm sure I've found a mistake.
var id = "loopBlock"+i+1;
you have to replace with:
var id = "loopBlock"+(i+1);
Example i is 2.
In first case you get: "loopBlock21"
In second (my) case, you'll get "loopBlock3"
The problem is in operator precedence. Since in this line
var id = "loopBlock" + i + 1;
you have two + (unary plus) operators with the same precedence they will act as a string concatenation operators, because one of the operands is a string ("loopBlock").
In your case you want to group i + 1 with parentheses to make the expression evaluate first as arithmetic addition operator. After that string concatenation with "loopBlock" will produce expected result:
var id = "loopBlock" + (i + 1);
Demo: http://jsfiddle.net/0091n9tt/
I think you're problem in is this line:
document.getElementById(id).getElementsByTagName('div')[0].innerHTML = "bye";
What you are actually doing is trying to gett divs inside the newly created div (loopBlock), which is empty.
You already have a reference to the block you want to modify the innerHTML; you can simply use it like this:
tempLoop.innerHTML = "bye";
So you're for loop would look like this:
for (i=0; i<5; i++){
var tempLoop = loopObject();
functionCodeDiv.appendChild(tempLoop);
tempLoop.innerHTML = "bye";
}
Note that you don't need the id anymore.
I’m having trouble storing an input element in a JavaScript variable. Please see the code below. The commented out bits do not work. The code works as it is; however, it is not DRY. It is overly verbose. Storing the element in a variable would clean things up, but when I attempt to do that (and push the value to the x array) I get an “Uncaught type error: cannot read property value of null”.
Please see the markup and script attached. Why do I get this error when I use the variable form of document.getElementById, but not when I hardcode the element over and over?
JavaScript:
var x = [];
var y = [];
//var xInput = document.getElementById("xInput");
//var yInput = document.getElementById("yInput");
//var dataBox = document.getElementById("display");
function insert() {
x.push(document.getElementById("xInput").value);
y.push(document.getElementById("yInput").value);
clearAndShow();
}
function clearAndShow() {
//Clear fields
xInput.value = "";
yInput.value = "";
//Show output
document.getElementById("display").innerHTML = "";
document.getElementById("display").innerHTML += "X: " + x.join(", ") + "</br>";
document.getElementById("display").innerHTML += "Y: " + y.join(", ") + "</br>";
}
HTML:
<body>
<div class="container">
<form>
<h2>Delay Discounting - Enter X (Delay) and Y (Value)</h2>
<input id="xInput" type="number" placeholder="x (delay)" />
<input id="yInput" type="number" placeholder="y (value)" />
<input type="button" value="save/show" onclick="insert()" />
</form>
<div id="display"></div>
</div>
</body>
Paul Roub left a comment that fixed it. I was loading the script in the head of the HTML document with the rest of my source files. This was problematic because the elements referenced by the JS were not created on the DOM yet. When I moved the script to the end of the HTML document, I could then store the element in the variable.
MyServlet forwards to Mypage.jsp as
request.getRequestDispatcher("/pages_homepage.jsp?value="+count).forward(request, response);
where count is an integer value generated
Below is my JSP code(Mypage.jsp),
<body onload="getPage('<%request.getParameter("value");%>')">
<div id="app"></div>
</body>
Below is my javascript code,
function getPage(match){
var arr = new Array();
var ele = document.getElementById('app');
for(var i=0;i<match;i++){
var newdiv = document.createElement("label");
newdiv.id = arr[i];
newdiv.value="Page";
ele.appendChild(newdiv);
}
}
What I want is that, I want 'Page' to be displayed 'match' number of times. But I'm not being able to do so by the above code. Their might be something wrong with my js code. Can anyone suggest me any corrections?
Thanks in advance.
LIVE DEMO
Taking in consideration that your page has something like:
<body onload="getPage(5)">
function getPage(n) {
var ele = $('#app');
var labels = ""; // An empty string will be populated with labels elements:
for(var i=0; i<n; i++){
labels += '<label id="'+ i +'"> Page </label>'
}
ele.append( labels ); // append only once outside the loop!
}
The result will be:
<label id="0"></label>
<label id="1"></label>
<label id="2"></label>
<label id="3"></label>
<label id="4"></label>
If you want to start from 1 instead of 0 use:
labels += '<label id="'+ (i+1) +'"> Page </label>'
Note: ID starting with (/ containing only) a number - is only valid in HTML5
Your Code is working and i have tested it
Since you don't have any content in the label tag hence it is not visible in browser
Secondly a small error
in 6th line of js code
newdiv.id = arr[i];
arr[i] is not given any value hence change it with
newdiv.id = i;
enjoy your code
Thanks everyone for their help but I think I got the answer,
Instead of
<body onload="getPage('<%request.getParameter("value");%>')">
I wrote,
<body onload="getPage('<%=Integer.parseInt(request.getParameter("value"))%>')">
But thanks everyone again for their useful pointers.
I am trying to put some html mark-up inside an array for retrieval later. My editor throws a syntax error on the description1 line, I can't figure out why. Any help would be much appreciated. Code below. Thanks A
var modalcontent = {
description1 : '<div id = "description"><div class = "tbc">
<label class = "tbc" for = "tbc">Description</label>
</div>
<div class = "tbc">
<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">
</div>
</div>
<!--end description div-->'
}
You have an unclosed string literal. JavaScript strings are not multi line by default.
var modalcontent = {
description1 : '<div id = "description"><div class = "tbc"> '+
'<label class = "tbc" for = "tbc">Description</label>'+
'</div>'+
'<div class = "tbc">'+
'<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+
'</div>'+
'</div>'+
'<!--end description div-->'
}
(fiddle)
Alternatively, you can create multi line string by using the \ character, those only work in newer implementations. See this related question or the language specification.
Note: It's usually not the best idea to store HTML in strings, it makes it harder to debug and work with. You can usually use templates. It's not that there are no good use cases, it's just rarely the case.