Im relatively new to javascript. I have an ID
btnradio_-1-1_4_-1
for an input button but it is being read as a Numeric Separator and giving me the error
Uncaught SyntaxError: Numeric separators are not allowed at the end of numeric literals
The ID is coming from a Model which reads all other data fine in the context. The format of the ID is as it is for tracking dynamic values on a razor/jquery web page, so its prefered that the ID format doesn't change.
How can you read it as just a string and not a Numeric Separator variable? I need the ID to call in a getElementByID().
I tried storing it in a separate string variable, as well as converting it to a string then using it, but I get the same error.
EDIT: My javascript is embedded in a razor section if that is causing any conflicts. I am unsure if its relevant or not. It is also alongside some jQuery.
#section scripts {
<script>
...
document.getElementById(#Model.ItemIDs[3]).className += "btn-check:active";
...
</script>
}
EDIT: I had the wrong ID pasted in the question. It has been corrected and should make more sense than the last one in the context
Related
I have an html string that I getting from a backend server.
I am trying to view css properties and extract the value of a first occurrence of a background-color in a HTMLStyleElement. However the format of the HTMLStyleElement is different than I expected.
How might I find the first occurrence of the property in the css without searching through the string if possible?
I am using NodeJS with Express and the PUG view engine.
I am attempting to check if an array contains a certain string. I have tried the builtin javascript methods such as:
array.includes(str)
array.indexOf(str) > -1.
However neither of these options seem to work. How can I check if an array contains a certain string in PUG?
if example_array.length > 0
span() Array contains elements! // This works and appears on page
if example_array.includes('example string') // This does not work
span() Array includes example string! // This does not appear on page
If you want to run inline JS in your template you have to mark your code as unbuffered.
https://pugjs.org/language/code.html#unbuffered-code
if example_array.length > 0
span() Array contains elements!
- if (example_array.includes('example string'))
span() Array includes example string!
Note the "-" in front of the "if" on line 3.
Since this is a literal js expression now the parantheses are required aswell.
This kept me busy for hours so I wanted to share my own solution. While the answer is correct when checking for a string directly, remember you may need to add .toString() if you're checking from a variable:
- if (example_array.includes(myVariable.toString()))
Hopefully this saves someone some time!
Using xml2js to parse an XML file, I need to retrieve the value of an attribute which contains a hyphen in its name
<item cdr-id="1234">
<name>some text</name>
</item>
At the point where I'm trying to retrieve cdr-id, I already have a variable item which points to the item element. I've verified it's pointing to the proper node with
console.log(item.name);
and that returns the expected value some text. But when I try
console.log(item.$.cdr-id);
I get the completely reasonable error ReferenceError: id is not defined (I'd have been more surprised if id wasn't treated as a separate token).
Likewise,
console.log(item.$."cdr-id");
gets the message SyntaxError: Unexpected string.
Throwing JSON.stringify around it
console.log( JSON.stringify(item.$));
reveals the original attribute name: {"cdr-id":"CDR0000040222"}
Not having hyphens in the name in the first place just kicks the problem down the road a bit. Failing that, it looks like providing a custom attribute name processor is the way to go, but that smacks of being "too clever" with potential for confusion if anyone ever has to update this code.
Is there a better way to do this?
do like
console.log(item.$["cdr-id"]);
I'm developing a portlet for WebSphere Portal 6.1, with JSP/JSTL, pure javascript, no AJAX frameworks, with a JSP that shows a send feedback form and, when submitted, redirects to another JSP to show the user the success of the operation.
I use javascript to get the values of the form fields by using document.getElementById() function. For example:
var valorAsunto = document.getElementById("asunto").value;
where "asunto" is the ID of a text field in my form. Also my form has the following structure:
<form name="formularioCorreo" id="formularioCorreo" method="post" action="<portlet:renderURL><portlet:param name="nextTask" value="sendFeedback"/></portlet:renderURL>">
That works OK, but I'm having trouble when trying to build the <portlet:renderURL> tag from that javascript values: when I try to concatenate a string for the renderURL and then reassign to form action like this:
var valorAction = '<portlet:renderURL><portlet:param name="nextTask" value="sendFeedback"/><portlet:param name="asunto" value="'+valorAsunto+'"/></portlet:renderURL>';
document.formularioCorreo.action = valorAction;
document.formularioCorreo.submit();
The resulting string, when application is deployed, has the structure:
/wps/myportal/<portletpath>/!ut/p/c5/<a very long random sequence of
numbers and letters>/
So one can't figure out where the parameter values are, but if I print the assigned values it shows something like:
asunto: '+valorAsunto+'
instead of
asunto: this is a sample subject
I've been trying to use some other ways to concatenate the string; for instance with a StringBuffer, as shown on http://www.java2s.com/Tutorial/JavaScript/0120__String/StringBufferbasedonarray.htm
and also javascript functions like encodeURI()/decodeURI(), replace(), etc. but I just can't get either the URL with the right parameter values or the URL encoded in the structure shown above (the one with the long sequence of chars).
Sometimes I manage to get the right parameter values, by manually replacing in the valorAction assignation all the "<" for "<" and all the ">" for ">" before the concatenation, and then doing the following:
var valorAction = valorAction.replace(/</g,"<").replace(/>/g,">");
Then I get the following string:
<portlet:renderURL><portlet:param name="nextTask" value="sendFeedback"/><portlet:param name="asunto" value="this is a sample subject"/></portlet:renderURL>
which is OK, but when it has to redirect to the results page it shows an error like this
Error 404: EJPEI0088E: The resource <portlet:renderURL><portlet:param
name="nextTask" value="sendFeedback"/><portlet:param name="asunto"
value="this is a sample subject"/></portlet:renderURL> could not be
found.
Does someone know how to transform that string to the right format to be rendered?
Does someone know any other way to "inject" that parameter values to the renderURL?
I'd like to know also if it is possible to pass that parameter values from javascript to JSP so I could put that values in a HashMap of parameters to use with the PortletURLHelper.generateSinglePortletRenderURL() method, in case the former is not possible.
Thank you.
Update 1:
In my doView() I use the following, in order to make the redirection:
String targetJsp = "/_Feedback/jsp/html/FeedbackPortletView.jsp";
String nextTask = request.getParameter("nextTask");
//(... I have omitted code to conditionally select targetJsp value, according to nextTask value ...)
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(targetJsp);
rd.include(request, response);
This is just a new JSP inside my portlet, not a different portal page. I do use request.getParameter() to get the values for my form fields from my doview():
String subjectFeedback = request.getParameter("asunto");
String bodyFeedback = request.getParameter("mensaje");
String emailFeedback = request.getParameter("emailFeedback");
I don't see the need to include hidden fields if my form has the fields named above. In fact, what I'm trying to do is to pass the values the user entered in these fields as request parameters, but the values I get by this means are the following:
subjectFeedback: "'+valorAsunto+'"
bodyFeedback: "'+valorMensaje+'"
emailFeedback: "'+valorEmailFeedback+'"
I get the above values when using concatenation by "+"; when I use StringBuffer I get the following values:
subjectFeedback: "'); buffer.append(valorAsunto); buffer.append('"
bodyFeedback: "'); buffer.append(valorMensaje); buffer.append('"
emailFeedback: "'); buffer.append(valorEmailFeedback); buffer.append('"
Does someone know any other way to "inject" that parameter values to the renderURL?
There are two IBM guides on that topic.
Portal 6.1 and 7.0 Advanced URL Generation Helper classes
How to create a link to a portlet (Standard API) that passes parameters to that portlet
How are you redirecting to the other page? Is it a different portal page or just a new JSP page inside your portlet?
You don't need to inject any parameters to the render URL. Have a form whose action targets to a renderURL. Now to pass information to your portlet's doView() method, you can have hidden fields in the form ,then populate them using JavaScript and then submit the form. In the doView() method, you can use request.getParameter() to get the parameters.
Well, sometimes the most obvious things happen to be the way to the solutions.
I was too busy trying to find elaborated causes for that situation that I did not checked for this at all:
My form fields were correctly identified by different id, but they weren't set their name properties.
With the help of a work partner we could figure out that, so assigning the same value of id for name on each form field did the trick.
So, I ended up skipping that reassigning action thing, because the field values are being set as request parameters, as it should be.
Thanks for the help.
Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \