In my jsp I use <%String base = (String)application.getAttribute("base");%>
I tried to use 'base' in javascript but not work. Below is my javascript:
<script>
var newBase = <%=base%>;
</script>
Can anyone help me to solve this?Thanks
This is the eplanation www.w3schools.com give for location object property pathname:
pathname: Sets or returns the path name of a URL
In our case the javascript file wich is in your context.
The first element is that pathname is the context
So you split the attribute (see the split method in javascript String) and return it.
This should do.
<script language='javascript'>
function servletContext() {
var sc = window.location.pathname.split( '/' );
return "/"+sc[1];
}
</script>
You can rather try it out like this ,
set the value to the hidden field ,
input type="hidden" id="hidVal" name="txt2" value="${base}"/>
And in your java script ,
<script>
var x = document.getElementById('hidVal').value;
alert(x);
</script>
Update :
var newBase = '<%=base%>';
You are missing the quotes to treat the value as string .
Hope this helps !!
Related
I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"
I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax
In the CMS I am building, record names have to be unique (they are URL keywords). In order to achieve this with blog posts, I am attempting to prefix blog post titles with date("Y-m-d") in PHP.
I have a "title" input text field, in which the title is entered, a "keyword" text field which automatically "slugs" the title in order to turn it into a URL keyword.
I'm having trouble figuring out how to prefix the slugged title with the date.
Here's the code:
<input name="title" type="text" id="title" />
<input name="keyword" type="text" id="slug" />
<script type="text/javascript">
$(document).ready(function(){
$("#title").slug();
});
</script>
This part works. The title successfully turns into a keyword with dashes for spaces, eliminating special characters, etc.
I tried including the date by adding a hidden field with the date as the value and accessing its value with the getElementById function. I attempted to rework the javascript to concatenate the slugged title with the date:
<input type = "hidden" id = "postdate" value = "<?php echo date("Y-m-d"); ?>-" />
<script type="text/javascript">
$(document).ready(function(){
var getDate = document.getElementById('postdate');
var doSlug = $("#title").val();
var slugString = getDate + doSlug;
$("slugString").slug();
});
</script>
But I'm obviously not working properly with the javascript.
The output I'm after would be: "2013-10-09-title-of-this-blog-post"
Where am I going wrong?
Working Fiddle
I suggest you to do a little tweak to the plugin to be able to do what you want.
As you can see in the feedle above i add two new configuration parameters
prepend: null, // String to be prepended the sluged string
append: null // String to be appended the sluged string
and on the makeSlug function i just add this two conditionals
if(typeof settings.append === 'string')
slug = slug + '-' + settings.append;
if(typeof settings.prepend === 'string')
slug = settings.prepend + '-' + slug;
Now you can prepend or append a string to the slugfy version of your string
$("#title").slug({
prepend: '2010-10-13',
append: 'YAYY'
});
If you decide to use this approach, here is how to use with your html
$(document).ready(function(){
$("#title").slug({
prepend: $('#postdate').val()
});
});
How about:
$(document).ready(function(){
var getDate = $('#postdate').val(); // get the value of the postdate id, not the element.
var doSlug = $("#title").val();
var slugString = getDate + "-" + doSlug;
$('#title').val(slugString);
$('#title').slug(); // if needed.
});
The jQuery slug() function is changing the input value to be "slugged". You can't set it to "slugString", because that's a variable, not a dom element. If necessary, you can "reslug" the input value after setting it with val().
Edited to fix the getDate variable issue that #Oswaldo Acauan picked up
#(Html.ActionLink("Link Label",
"ActionMethodName",
"ControllerName",
null, // parameter object, then html object
null))
produces
Link Label
If I want to reference the /ControllerName/ActionMethodName/id in a JavaScript template for the Edit or New link, how would I assign that to a JavaScript variable?
attempt:
<script type="text/javascript">
var actionUrl = '#(Html.ActionLink("","ActionMethodName",
"ControllerName",null,null))';
</script>
but at that point, I would have to use Javascript to remove the unwanted <a href... characters in the string.
#Url.Action("ActionMethodName", "ControllerName") will generate a path.
<script type="text/javascript">
var actionUrl = #Html.Raw(Json.Encode(Url.Action("ActionMethodName", "ControllerName")));
</script>
or if you already have this actionLink somewhere inside the page you could use it directly:
var actionUrl = $('#mylink').attr('href');
Just ensure to provide a unique id in order to simplify the selection:
#(Html.ActionLink(
"Link Label",
"ActionMethodName",
"ControllerName",
null,
new { id = "mylink" })
)
I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname.
The properties are the same as for the location object.
Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.
If by "relative URL" you mean the part of the string after the first single /, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single / in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp --> Out: /my/page.jsp
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
URL.getRelativeURL
There's an public-domain extension for the standard URL object called getRelativeURL.
It's got a few cool tweaks like force reload, you should check it out!
Try it live. View on Gist.
Example usage
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";
don't forget that \ is an escape character in strings, so if you would like to write regex in strings, ensure you type \ twice for every \ you need. Example: /\w/ → "\\w"
Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
we want to url as below:
/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie,
var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
i think you guys got that point if you have still doubt let me know please
and to see changes in code by inspecting:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>