JavaScript string literal in object literal syntax error - javascript

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.

Related

How to dynamically add ng-readonly attribute

In my JS code, I want to create an input element with ng-readonly attribute. My code is as follows:
var newClientNameInputBox = document.createElement("input");
newClientNameInputBox.name = "clientNames";
newClientNameInputBox.type = "text";
newClientNameInputBox.className = "form-control";
newClientNameInputBox["ng-readonly"] = "setReadonly";
However, newClientNameInputBox turns out to have only the attributes name, type, and class. The ng-readonly attribute is missing. How should I go about adding an ng-readonly attribute?
You can make use of: Compiler (aka $complie) is an AngularJS service which traverses the DOM looking for attributes. https://docs.angularjs.org/guide/compiler
Something like this should work:
var template = '<input name="clientNames" type="text" class="form-control" ng-readonly="setReadonly" />';
var newClientNameInputBox = angular.element(template);
var $compile = ...; // injected into your code
var scope = ...; // { setReadonly : true }
var parent = ...; // DOM Parent where you want to drop your input
var compiledElement = $compile(newClientNameInputBox)(scope);
parent.appendChild(compiledElement);

Dynamically generated HTML selectedIndex returns null

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.

Can't read property 'style' of null from dynamic html code

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

How to dynamically add the content in jsp page using javascript?

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.

Pass variable in document.getElementByid in javascript

I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product

Categories