Retrieve a hiddenfield value through javascript - javascript

I am using the following javascript to retrieve a value of a asp hidenfield.
var pagemode
function setValue() {
pagemode= document.getElementById('<%#litTest.ClientID%>').value;
}
function Item_load(sender, eventArgs) {
window.location.href = "Request.aspx?Request_ID=" + eventArgs.get_item().getMember('Request_ID').get_value() + "&ListType=" + pagemode;
}
The value to the hiddenfield is loaded in page load in code behind. I need to pass the value as a querystring and it comes as undefined.
I would really appreciate if anyone can help.

So you don't get a reference to your hiddenfield? Try this:
<script type="text/javascript">
var litTestID = '<%= litTest.ClientID %>';
function setValue() {
var pagemode = $(litTestID).value;
// ...
}
</script>
Otherwise use the javascript debugger to inspect the order of executino and the variable values.

Related

Asp.net mvc passing a C# model to Javascript file

I want to pass the value i got it from model to the java-script function
<script type="text/javascript">
var checkin = #Model.Parameters.Checkin.ToString("dd-MM-yyyy");
var checkout = #Model.Parameters.Checkout.ToString("dd-MM-yyyy");
</script>
this function that i want to pass model chick-in and chick-out value to it:
$('document').ready(function () {
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
i tried many solution but it didn't work yet .
any advice, thanks
if the #Model.Parameters.Checkin and #Model.Parameters.Checkout not null then Try:
<script type="text/javascript">
$( document ).ready(function(){
var checkin = '#Model.Parameters.Checkin.ToString("dd-MM-yyyy")';
var checkout = '#Model.Parameters.Checkout.ToString("dd-MM-yyyy")';
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
Just you miss '. and also change $('document').ready(function () { }) to $(document).ready(function () { }).
you must write all script into a .cshtml file. #Model.Parameters.Checkin.ToString("dd-MM-yyyy") never work into a .js file.
Because, In .cshtml, when the the page is render then it white to HTTP response stream as a string.
In MVC, you can use following code:
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>

Activate javascript string onload on code behind C#

Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);

How to get return value from javascript through JSP?

function testing(){
var e = document.getElementById("selectBranchId");
var strUser = e.options[e.selectedIndex].value;
return strUser;
}
function test(){
var resultValue = testing();
alert(resultValue);
}
How can I get the value of resultValue in JSP? I tried using request.setAttribute but I am getting error variable resultValue can't be resolved. What can be the solution?
As JavaScript runs on the client side and JSP/Scriptlet is running on the server-side.
So if you want to access any of your JavaScript variable in JSP/Java/Server Side, then either
Submit it as a Hidden form field
or Pass it via Ajax Request
The variable doesn't exist beforehand in the JspWriter. Consider your javascript in two categories; before the page is written and after.
<html>
<head/>
<body>
<%!
function testing(){
var e = document.getElementById("selectBranchId");
var strUser = e.options[e.selectedIndex].value;
return strUser;
}
%>
<% testing(); %>
</body>
</html>
See this answer for more information.

Transfering a variable from one html document to another with a popup-window in Javascript

So I have a main html-document called commit_PNG.html and in this document i have two simple string variables i want to use in the other html-document called popup.html. At the moment i have a function like this:
<script type="text/javascript">
function PopUpFenster(id) {
myWindow = window.open('popup.html?id='+id, 'Info window', 'height=350, width=800');
}
</script>
In the second html-document I want to work with the string variables. I need a solution that work something like this in popup.html:
var string1 = "http://www.test.com/"+ commit_PNG.stringvariable1;
var string2 = "http://www.test.com/"+ commit_PNG.stringvariable2;
I'm not sure but I either need to take them directly from commit_PNG.html or parse them someone with the window.open() method.
Use the hash part to transfer a JSON object like this:
In commit_PNG.html:
var myStrings = {
str1:"my first str",
str2:"my second str"
}
function PopUpFenster(id) {
var myUrl = "popup.html?id="+id+"#"+encodeURIComponent(JSON.stringify(myStrings));
window.open(myUrl , "Info window", "height=350, width=800");
}
Then in your popup.html Just do:
var myData = JSON.parse(decodeURIComponent(window.location.hash.substring(1)));
alert(myData.str1 + " " + myData.str2);
It's a great way to pass date in a url. You get to pass a JSON object and using stringify with encodeURIComponent makes it a safe string for the URL.
Using the hash part, makes sure it's not sent to the server.
commit_PNG.html
<script type="text/javascript">
function getVariables(){
return {
stringvariable1: 'v1',
stringvariable2: 'v2'
};
}
function PopUpFenster(id) {
myWindow = window.open('popup.html?id='+id, 'Info window', 'height=350, width=800');
}
</script>
popup.html
<script type="text/javascript">
var parentWindow = window.opener;
var variables = parentWindow.getVariables();
var string1 = "http://www.test.com/"+ variables.stringvariable1;
var string2 = "http://www.test.com/"+ variables.stringvariable2;
</script>

Display a div on pageload

I am passing div name in the query string from one html page and retrieving that div name on the other html page. Now I want to display that specific div on the page.My code is
function onLoad()
{
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block"; //error is in this line
}
But I am getting an error as "object expected". please help me
The window.location.search property returns the part of the URL that follows the ? symbol, including the ? symbol.
So for example it might return ?paramname=paramvalue. When you call substring(1) on it you get paramname=paramvalue which is what gets passed to the document.getElementById function which obviously is wrong because such element does doesn't exist on your DOM.
You could use the following javascript function to read query string parameter values:
function onLoad() {
var divname = getParameterByName('divname');
document.getElementById(divname).style.display = 'block';
}
This assumes that you have a query string parameter name called divname:
?divname=some_div_name
Adjust the parameter passed to the getParameterByName function if your query string parameter is called differently.
You might also want to introduce error checking into your code to make it more robust:
function onLoad() {
var divname = getParameterByName('divname');
var divElement = document.getElementById(divname);
if (divElement != null) {
divElement.style.display = 'block';
} else {
alert('Unable to find an element with name = ' + divname);
}
}
What I am suggesting is place your js at the end of the html code (before </body> tag). Do not use a function.
<html>
...
...
...
<body>
...
...
...
<script>
var divname=window.location.search.substring(1);
document.getElementById(divname).style.display="block";
</script>
</body>
</html>
I have re-written my function and it is working, code is like this
function load()
{
var divname = window.location.search.substring(1);
var params=divname.split('=');
var i=1;
alert(params[i].substring(0));
document.getElementById(params[i].substring(0)).style.display='block';
}

Categories

Resources