Accessing HTML5 Custom Data Attributes for multiple instances of webpart - javascript

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');

Related

Combine JQuery with Thymeleaf

I have this JQuery function used in a Thymeleaf template to submit the template to a specific URL, based on the value selected in a dropbox object, but it seems not to work
$('#selectAuthorizedDriverId').change(
function() {
var link = /*[[#{/deviceDriver/updateauthorizeddriver}/$('#selectAuthorizedDriverId').val();]]*/ "";
$('#deviceFormId').attr('action', link);
$('#deviceFormId').submit();
});
Do not use thymeleaf
var link = "/deviceDriver/updateauthorizeddriver/" + $(this).val();

Automatically Filtering Items By Vendor During Creation of a Record

I have a set of scripts that I'm using that interact with each other. I use a client, user event and suitelet script to create a button that, when pressed, opens a popup with a list of items filtered by vendor.
It works fine when I'm in edit however when I use it while creating a record problems arise. Since the record to be created has no vendor or id I can't retrieve an item by vendor. What I'm trying to do is to have the Suitelet retrieve the info from the vendor field that is entered prior to it being saved. Therefore I can filter all the items by vendor and add the necessary items in one go. Is this possible? Am I able to access the info before it is submitted.
Below are the Client and Suitelet. The User Event is just a call to the suitelet so for the sake of brevity I left it out.
Client Script
function addItemButtonCallback(data){
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', data);
nlapiCommitLineItem('inventoryitem');
}
function addItemButton() {
var id = nlapiGetFieldValue('id');
if (id != "") {
var url = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1') + '&poId='+id;
window.open(url, '_blank', 'width=500,height=500');
}
}
Suitelet
function suitelet(request, response){
if(request.getMethod() == 'GET') {
var form = nlapiCreateForm('Add Item');
form.addSubmitButton('Submit');
var itemfield = form.addField('custpage_val', 'select', 'Item');
var id = request.getParameter('id');
var rec = nlapiLoadRecord('purchaseorder', id);
var vend = rec.getFieldValue('entity');
var search = nlapiSearchRecord(...search parameters...);
for (result in search){
if (search[result].getValue('vendor') == vend){
itemfield.addSelectOption(search[result].id, nlapiLookupField('inventoryitem', search[result].id, 'itemid'));
}
}
response.writePage(form);
} else {
var data = request.getParameter('custpage_item');
response.write('<html><body><script>window.opener.addItemButtonCallback("'+data+'"); window.close();</script></body></html>');
}
}
Use nlapiGetFieldValue('entity') on the clientscript and pass it to the Suitelet using a query parameter just like you are doing with poId (if you do this you might not even need poId after all + no need to load the record on the suitelet).
Also, you might want to optimize your code by running one search passing an array of itemids instead of calling nlapiLookupField for each item.
You might need to modify your beforeLoad so the entity is inserted dynamically when the button is pressed (I cant remember if clientscript button does this) . Something like this:
var suiteletURL = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1');
var script = "var entity = nlapiGetFieldValue('entity'); var url = '" + suiteletURL + "'&entityId=' + entity;window.open(url, '_blank', 'width=500,height=500')";
var button = form.addButton('custpage_addItemButton', 'Add Item', script);

Compare variable values in scriplet and javascript

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

JavaScript - How do I open a new page and pass JSON data to it?

I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?
If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html
In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).
Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:
/*
submit JSON as 'post' to a new page
Parameters:
path (URL) path to the new page
data (obj) object to be converted to JSON and passed
postName (str) name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
// convert data to JSON
var dataJSON = JSON.stringify(data);
// create the form
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', path);
// create hidden input containing JSON and add to form
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", postName);
hiddenField.setAttribute("value", dataJSON);
form.appendChild(hiddenField);
// add form to body and submit
document.body.appendChild(form);
form.submit();
}
Use some PHP like this on the target page to get the JSON:
$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );
Or, more simply for JavaScript:
var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );
Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.
Hmm, for example, you have object
var dataObject = {
param : 'param',
param2 : 'param2'
};
You can translate it into string, using JSON.stringify method
var dataObjectString = JSON.stringify(dataObject);
Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)
var dataObjectBase64 = base64encode(dataObjectString);
You will get something like this
e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307
Then you can pass this string as a parameter:
iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"
Finally, reverse actions on the loaded page.
You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.
Something like this...
Im using JQUERY AND UNDERSCORE(for template purpose)
this is the template
<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
<input type='hidden' name='json' id='<%= valueId %>' />
</form>
you can then post use it on javascript
function makePost(){
var _t = _.template("use the template here");
var o = {
method : "POST",
action :"someurl.php",
name : "_virtual_form",
id : "_virtual_form_id",
valueId : "_virtual_value"
}
var form = _t(o); //cast the object on the template
//you can append the form into a element or do it in memory
$(".warp").append(form);
//stringify you json
$("#_virtual_value").val(JSON.stringify(json));
$("#_virtual_form_id").submit();
$("#_virtual_form_id").remove();
}
now you dont have to be worry about the lenght of you json or how many variables to send.
best!
If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.
Something like:
window.open(yourUrl + '?json=' + serializedJson)
Assume if your json data
var data={"name":"abc"};
The page which sends JSON data should have the following code in the script tag.
$.getJSON( "myData.json", function( obj ) {
console.log(obj);
for(var j=0;j
<obj.length;j++){
tData[j]=obj;
//Passing JSON data in URL
tData[j]=JSON.stringify(tData[j]);
strTData[j]=encodeURIComponent(tData[j]);
//End of Passing JSON data in URL
tr = $('\
<tr/>
');
//Send the json data as url parameter
tr.append("
<td>" + "
" +Click here+ "" + "
</td>
");
}
});
The page which receives the JSON data should have the code.
<html>
<head></head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<body>
<p id="id"></p>
</body>
<script type="text/javascript">
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.jsonDATA);
var name=data.name;
console.log(name);
document.getElementById("id").innerHTML=name;
} catch (err) {
alert(err + "\nJSON=" + q.team);
}
</script>
</html>

How to get the Id of an object which is added in codebehind using javascript

Example:i am assigning this in .cs page
HiddenField hdnCharacter = new HiddenField();
HiddenField hdnMaxCharsError = new HiddenField();
Label lblMaxChrs = new Label();
lblMaxChrs.ID = "lblMaxchrs";
hdnMaxCharsError .ID = "hdnMaxCharsError ";
hdnCharater.ID = "hdnCharater";
How to get his ID and values using javascript in.js file i am trying to do custom control.so i dont have any page to add in aspcontrol. TR
use this way :
var id1=document.getElementById('<%= lblMaxchrs.ClientID %>');
var id2=document.getElementById('<%= hdnMaxCharsError.ClientID %>');
var id3=document.getElementById('<%= hdnCharater.ClientID %>');
even while you write the asp code. While rendering in the HTML format the field would be hidden but would be present in the page. you can use :-
var id1=document.getElementById('lblMaxchrs');
var id2=document.getElementById('hdnMaxCharsError');
var id3=document.getElementById('hdnCharater');
And in order to retrieve the values of each indevidual you can use :-
var text1=id1.textContent;
var text2=id2.textContent;
var text3=id3.textContent;

Categories