Maybe a chicken/egg problem.
Based on this answer: https://stackoverflow.com/a/27190520/1438215
I want to use javascript to populate the value of an asp.net hidden field (as soon as it's possible), and then access the value of that populated field in the server-side Page_Load event.
Sample:
aspx portion:
<div id="div_BrowserWindowName" style="visibility:hidden;">
<input type="hidden" name="ctl00$ctl00$BodyContent$MainContent$hf_BrowserWindowName" id="BodyContent_MainContent_hf_BrowserWindowName" />
</div>
<script type="text/javascript">
function PopBrowserWindowName() {
if (typeof window.name != undefined) {
if (window.name == '') {
var d = new Date();
window.name = '_myWnd_' + d.getUTCHours() + d.getUTCMinutes() + d.getUTCSeconds() + d.getUTCMilliseconds();
}
var eDiv = document.getElementById('div_BrowserWindowName');
var e = eDiv.getElementsByTagName('input')[0];
e.value = window.name;
alert(e.value);
}
}
window.onload = PopBrowserWindowName();
</script>
aspx.cs portion (page_load) event:
if (hf_BrowserWindowName != null)
{string winID = hf_BrowserWindowName.Value;}
This does works during postbacks, but does not work on the page's initial load.
Prior to Page_Load, there is no HTML or JavaScript because the Response has not been sent to the client yet. You need to learn the ASP.NET Page Lifecycle.
You can use server side code to populate the information, or after the page is sent to the client you can have some JavaScript populate the information.
Related
I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer
i'm using JavaScript to make some small customization in default SharePoint 2013 issue tracker. When user submit an issue (default SharePoint function presave) JavaScript should redirect document to new URL. Everything works fine in Firefox in IE but from unknown reason redirection doesn't work in Chrome.
I'm used location, replace.href, assign etc - result the same - chrome just save the form without redirection. Can you give me any hint why it doesn't work?
I'm using SP 2013 online (and i don't have access to SP designer)
<script src="/sites/SiteAssets/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/sites/SiteAssets/Scripts/sessvars.js"></script>
<script language="javascript" type="text/javascript" src="/sites/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript">
// Here i have small function to get email from sharepoint peoplePicker field
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
if(userInfo != null)
{
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
function PreSaveAction(){
// check if there is attachment
if ($('#onetidIOFile').get(0).files.length === 0) {
} else {
OkAttach() //attach file to form
}
//get email from field
var RequestApprover = getEmailFromPeoplePicker('Assigned To');
//create link for redirection with email at the end (ill use it latter for sending emails)
var targetUrl = '/sites/SitePages/RedirectDestination.aspx' + '#' + RequestAprover;
//window.location.href = targetUrl;
//location.replace(targetUrl);
//window.location.assign(targetUrl);
// window.top.location.href = targetUrl;
window.location.assign(targetUrl); // <---------- redirection which works in IE and FireFox but not in Chrome
//window.location.href = targetUrl;
//window.location.assign(targetUrl);
//window.parent.location.href(targetUrl);
//setTimeout(function(){location.href = targetUrl},500);
return true;
}
</script>
I believe you should have "return false;" (instead of return true;) at the end of your PreSaveAction function implementation. Looks like in Chrome redirect takes more time then in other browsers, so Sharepoint continues usual form flow (e.g. continues to PreSaveItem etc.)
I would really appreciate some guidance. This is probably simple to some of you, but i can't figure it out.
Thanks for any input.
THE REQUIREMENT
I have a multi-tabbed control. One each tab, I have a custom reportviewer control.
I have added a custom attribute to the reportviewer in the code behind called "data-report-param".
I need to access the value of custom attribute "data-report-param" on the current tab on the client-side using javascript.
I have tried several ways including the following, but can't get to the value that is being created in the DOM.
MY CODE
//Attempt 1
var reportparamattribute = $('#ReportViewer1');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Attempt 2
var reportparamattribute = document.getElementById('<%= ReportViewer1.ClientID %>');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Also tried accessing the dataset
var reportparametervalue = reportparamattribute.dataset.report-param;
WHAT IS BEING PRODUCED IN THE DOM
('ctl00_m_g_66e41117_8ff5_4650_bf4d_7a4a25e326f3_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
('ctl00_m_g_9d6a6c3c_11d0_4e03_bbd2_b907172c437d_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
UPDATE- WORKING CODE BELOW
The key was passing the custom data attribute from the code behind and then accessing it in the $.cache as #popnoodles below indicated, and passing the clientID of the reportviewer into the javascript function to get to the current instance of the webpart child controls.
<input type="hidden" id="<%= ASP_SSRS.ClientID %>_myDataState"
onchange="compareUnitValues(this.id, this.parentNode.id, '<%= ReportViewer1.ClientID %>', '<%= ASP_SSRS.ClientID %>', '<%= btnSendHiddenField.ClientID %>');" />
<script type ="text/javascript">
function compareUnitValues(elemt, parent, reportviewerID, value1, value2) {
var myDataUnit = $("#" + elemt),
parentObject = $("#" + parent),
reportviewerObject = $("#" + reportviewerID),
ssrs = $("#" + value1),
btnSend = $("#" + value2);
var myDataUnitValue = myDataUnit.val();
var myDataUnitJSON = jQuery.parseJSON(myDataUnitValue);
var currentmyDataUnit = myDataUnitJSON.currentUnit.objectId;
var sessioncurrentObjectId = document.getElementById('<%= hiddenCurrentObjectId.ClientID %>').value;
ssrs.val(myDataUnitValue);
var currentReportViewerParam = $("#" + reportviewerID).attr("data-report-param");
if (currentmyDataUnit != currentReportViewerParam) {
btnSend.trigger("click");
}
}
FROM CODE BEHIND CREATE THE CUSTOM DATA ATTRIBUTE
ReportViewer1.Attributes.Add("data-report-param", parsedObjectId)
getAttribute will only give you the value that was in the generated or modified HTML not what is in the DOM. The data method never updates the HTML.
jQuery creates an empty object $.cache, which is used to store the values you set via the data method. Each DOM element you add data to is assigned a unique ID which is used as a key in the $.cache object.
Setting
$('#ReportViewer1').data('report-param', 1234);
Getting
var id = $('#ReportViewer1').data('report-param');
If you can use jquery why not just:
$("#reportviewer1").data('report-param');
I want to set a JavaScript variable from JSP without causing the entire page to reload. The code I have now sets the variable, but reloads the entire page as a side effect.
example.jsp:
<html>
<select name="country" id="country"onchange="getCountryI()">
<option value="">Select</option>
<option value="india">India</option>
<option value="aus">Austrila</option>
<option value="uk">U.K</option>
<option value="eng">England</option>
<option value="westindies">West-Indies</option>
</select>
</html>
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
</script>
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
Once you've downloaded the page, the only ways to update a local (in-page) variable from the server is to
a) reload the page, or
b) use AJAX (JSON/P, preferably) to get the variable.
HTTP is sessionless, which means that the server-side has no way to provide data to the page on the end-user browser unless the browser initiates contact. (Web/browser sockets aside, since they're HTML5-only. Do you really want the server side keeping a list of all the browsers that have ever needed a response and writing code to age them off? If you do, go right ahead--but it's easier to just AJAX it.)
I don't thing the problem is inside <%%>.
The event onChange has been called and this code is "refreshing" the page. (actually changing location)
window.location.replace("example.jsp?name=" + id);
Try debug.
This part is invalid :
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
</script>
The out.println will add invalid script content in the rendered page after refresh, also it will not be shown.
The <% %> part should be moved out of the script like this :
<script>
function getCountryI() {
alert(3);
var id = document.getElementById("country").value;
window.location.replace("example.jsp?name=" + id);
}
</script>
<%
String value = request.getParameter("name");
System.out.println("value is" + value);
out.println("valuevaluevalue" + value);
%>
You could use old-school Ajax:
<form action="..." method="..." target="foo">
...
<input type="submit" value="Submit">
</form>
<iframe id="foo"></iframe>
You could attach an onload event handler to the iframe so you can extract any info that you want:
var foo = null;
var iframe = document.getElementById("foo");
iframe.addEventListener("load", function() {
var win = iframe.contentWindow || iframe.contentDocument;
foo = win.foo
});
The response in the IFRAME could have a normal <script> tag that sets a global variable in that document, which you can access from the parent window.
EDIT: The key here is the target attribute on the FORM tag contains the value of the id on the IFRAME. That will cause the form to submit to the IFRAME, and load the response in the IFRAME.
Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.