On a button click, I'm calling a function in client side JavaScript.
doIt("TEST");
"TEST" is just the ID of label on my XPage.
In the function, I want to use the variable I passed as an ID. Something like:
function doIt(item){
alert(dojo.query("[id$=':item']").innerHTML);
}
OR
function doIt(item){
val = XSP.getElementById("#{id:item}").innerHTML;
alert(val);
}
I have also tried using this, which gives undefined:
val = dojo.query("[id$=':" + item + "']").innerHTML;
alert(val);
If I hard code the ID name like so, then I get the correct innerHTML of the element with the ID "TEST":
val = XSP.getElementById("#{id:TEST}").innerHTML;
alert(val);
Where is my syntax wrong when trying to write this very simple line of code used the passed variable?
The easiest way is to call your function with the complete id:
doIt("#{id:Test}")
and to use it in your function
function doIt(item){
alert(dojo.byId(item).innerHTML);
}
In the "onclick" client-event in the button, (inside XPage or CC), the client Ids can be computed, so you should put there something like this:
doIt("#{id:Test}"); // << "#{id:Test}" is computed in the server-side and the final client ID is sent to the browser
Then, in your cjs library (cjs libraries are not "evaluated" before sending to the client, so here you cannot use "#{id:Test}" expressions) you should have something like:
function doIt(idElement) {
var domElem = dojo.byId(idElement); // << here you get the element
}
Related
I would like to pass the action name and controller name to the #Url.action call within a Javascript function as variables. Is there a method to achieve this?
function list_onSelectionChanged(e) {
var strActionName = "Map";
var strControllerName = "PMO";
$("#content").load("#Url.Action(strActionName,strControllerName)");
}
You can't pass them from client-side code in this way because the server-side code has already run at that point. Specify them directly in the server-side operation:
function list_onSelectionChanged(e) {
$("#content").load("#Url.Action("Map", "PMO")");
}
Note that it looks like the syntax will fail because of nested double-quotes. However, keep in mind that the Razor parser identifies the server-side code separately from the client-side code. So this is the entire server-side operation:
Url.Action("Map", "PMO")
And the result of that operation is emitted to the client-side code:
$("#content").load("result_of_server_side_operation");
I was able to modify the script as follows:
function list_onSelectionChanged(e) {
var url = e.addedItems[0].path;
$.get(url, function (data) {
$("#content").html(data);
});
}
Even simpler:
$("#content").load(url);
This allows a variable to be passed for the url.
I'm trying to write a JS function that gets always the same file as parameter, like this:
function something(../content/id.csv){
//do something with this file
}
Is there a way to do it, without <file> input HTML tags?
Thanks for your help!
(Suggestion) Remove that param and use a local variable within that function.
But, if you want to call the function as follow something() and always will be that way, you can do this:
function something(path = '../content/id.csv'){
console.log(path);
}
something();
Resource
Default parameters
Unable to get the class value out side the getJSON scope. Alert declared inside displays value but outside doesn't.
// Getting classes based on classID
var ClassID = {"ClassID": item.ClassId};
var Class="";
$.getJSON('#Url.Action("GetClassesByID","Catalogue")', ClassID, function (Val) {
Class=Val;
alert("Inside Value " +Class);
});
html= html+'<div class="col-xs-7 col-sm-7 col-md-7 dvpadding isbnnum"><p><b>CLASS - ('+Class+')</b></p></div>';
I just want to update the Class mentioned in above html from the value got from ajax call
.getJSON is asynchronous. You're calling alert outside of it which is synchronous. You need to call a function once .getJson is successful like:
// Getting classes based on classID
var ClassID = {
"ClassID": item.ClassId
};
var Class = "";
$.getJSON('#Url.Action("GetClassesByID","Catalogue")', ClassID, logData(val));
function logData(val) {
Class = Val;
alert("Outside Value " + Class);
}
The reason you are getting an empty string is because of the way javascript and callbacks work.
This is what you are expecting to happen:
class = ""
$getJSON
Class = val
alert(Class)
This is what is happening though:
class = ""
$getJSON
alert(Class)
Class = val
The reason beeing that 'Class = val" is inside a callback which is basicly just an action that is supposed to happen once $getJSON is done.
However since $getJSON could take a few seconds, whatever is below $getJSON will be run first.
You can think of $getJSON as an assignment that happens. That line of code will execute VERY fast, just as fast as any other line of code. But because you provided a callback, the callback part of the line will only be executed once the JSON was actually fetched which could be at any time.
Edit: I misread the scope completely. Sorry.
So as you might know, Razor Syntax in ASP.NET MVC does not work in external JavaScript files.
My current solution is to put the Razor Syntax in a a global variable and set the value of that variable from the mvc view that is making use of that .js file.
JavaScript file:
function myFunc() {
alert(myValue);
}
MVC View file:
<script language="text/javascript">
myValue = #myValueFromModel;
</script>
I want to know how I can pass myValue directly as a parameter to the function ? I prefer to have explicit calling with param than relying on globals, however I'm not so keen on javascript.
How would I implement this with javascript parameters? Thanks!
Just have your function accept an argument and use that in the alert (or wherever).
external.js
function myFunc(value) {
alert(value);
}
someview.cshtml
<script>
myFunc(#myValueFromModel);
</script>
One thing to keep in mind though, is that if myValueFromModel is a string then it is going to come through as myFunc(hello) so you need to wrap that in quotes so it becomes myFunc('hello') like this
myFunc('#(myValueFromModel)');
Note the extra () used with razor. This helps the engine distinguish where the break between the razor code is so nothing odd happens. It can be useful when there are nested ( or " around.
edit
If this is going to be done multiple times, then some changes may need to take place in the JavaScript end of things. Mainly that the shown example doesn't properly depict the scenario. It will need to be modified. You may want to use a simple structure like this.
jsFiddle Demo
external.js
var myFunc= new function(){
var func = this,
myFunc = function(){
alert(func.value);
};
myFunc.set = function(value){
func.value = value;
}
return myFunc;
};
someview.cshtml
<script>
myFunc.set('#(myValueFromModel)');
myFunc();//can be called repeatedly now
</script>
I often find that JavaScript in the browser is typically conceptually tied to a specific element. If that's the case for you, you may want to associate the value with that element in your Razor code, and then use JavaScript to extract that value and use it in some way.
For example:
<div class="my-class" data-func-arg="#myValueFromModel"></div>
Static JavaScript:
$(function() {
$('.my-class').click(function() {
var arg = $(this).data('func-arg');
myFunc(arg);
});
});
Do you want to execute your function immediately? Or want to call the funcion with the parameter?
You could add a wrapper function with no parameter and inside call your function with the global var as a parameter. And when you need to call myFunc() you call it trough myFuncWrapper();
function myFuncWrapper(){
myFunc(myValue);
}
function myFunc(myParam){
//function code here;
}
I am just starting to get into JavaScript and couldn't find an exact scenario like this yet on SO, so I'm going to try my luck. I have two functions in an external JS file which create video feeds on our website:
function getVideos() {
//gets a list of videos
}
//callback function automatically called by getVideos()
function response(jsonData) { //can't change this line
var resp = document.getElementById("resp"); //can change this line and any subsequent lines
//parses data and populates resp
}
Then, from the HTML side, we just call getVideos() and the video feed will be created and populated.
However, I want to be able to pass any element ID I want into response() so that we can create multiple video feeds in different places on the same page. The thing is I can't change the function declaration of response() to include another parameter. Or at least I'm not led to believe I can by the company hosting our videos.
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
For more info, here is our JS code as it stands now (with the closure): http://www.thebearrocks.com/Other/js/videoFeed/createVideoFeed.js
And here is the tutorial on response() we're following from the host of our videos: http://support.brightcove.com/en/video-cloud/docs/making-media-api-calls-dynamic-script-tags
may be you can use arguments? like so:
function response(jsonData) { //callback function automatically called by getVideos()
var elemId = arguments.length<2 ? "resp" : arguments[1]+"";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
or, declare second argument what has default value like this:
function response(jsonData, elemId) {
elemId = elemId || "resp";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
in this case function can be called as with one or two arguments
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
No. Not the id variable needs to become global, but your local response function needs to for getting called back from the JSONP script - you're going to create a closure.
You can "export" it by calling
window.response = mylocalResponseFunction; // you did name that local var "response"