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
Related
I have MVC controller that returns a list containing a search string.
public ActionResult GetList(string searchString)
{
ViewData["searchString"] = searchString;
if (String.IsNullOrEmpty(searchString))
{
var persons = db.Persons.ToList();
return View(persons);
}
else{
var persons = db.Persons.Where(p=> p.Title.Contains(searchString)).ToList();
return View(persons);
}
}
In the view the list is displayed in a table. I want to highlight the searchString (or at most the td that contains the searchString). The following is my jquery where I attempted to achieve this. I have tried putting this bit of code in a separate .js script or in the view itself and I have also tried to change the code in several ways but it wouldn't work. It appears like the searchString remains null even if the content of my ViewData has changed.
$(document).ready(function () {
var textToHighligt = #ViewData["searchString"];
$("#simpleSearchButton").click(function () {
$("td:contains(textToHighligt)").css("background-color", "yellow");
});
});
I think this:
var textToHighligt = #ViewData["searchString"];
$("td:contains(textToHighligt)").css("background-color", "yellow");
should be concatenated:
var textToHighligt = '#ViewData["searchString"]'; //<---put in quotes
$("td:contains("+textToHighligt+")").css("background-color", "yellow");
I think you can do otherwise if it is not happening in the javascript file , create a hidden field and populate the value from the ViewBag
#Html.Hidden("hiddensearchString", (string)ViewBag.searchString)
For the ViewData
#Html.Hidden("FirstName", ViewData["searchString"])
and then the javascript read the value like this
var searchString = $("#hiddensearchString").val();
In you code you can also try this using of the single quote.
var textToHighligt = '#ViewData["searchString"]';
I am running a database app (sql backend). One particular form calls a value from another table using the follwing:
<td class=NewSalesOpCompany id="contactPostCode"><#externalfield SQL="Select POSTALCODE from wce_sales s join wce_linkto l on s.UNIQUEID = l.luniqueid left join wce_contact c on l.LEntityID = c.UNIQUEID where (s.UNIQUEID = '<#field field=uniqueid noedit static>')" ></td>
The above code populates the field with post-code data in text format which works fine. I then want to copy the data in that field to another field. I have tried the folwing but failed to get it to work.
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._POSTCODE;
if (oppPOSTCODE != parentPOSTALCODE)
{ oppPOSTCODE.value = parentPOSTALCODE.value;}
}
</script>
When executing the function I get "parentPOSTALCODE.value is undefined" error via firefox. I'm a bit of a newbie at this so any help would be appreciated.
Try this:
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._postcode;
if (oppPOSTCODE != parentPOSTALCODE)
{
oppPOSTCODE.value = parentPOSTALCODE.innerText;
}
}
</script>
Here is the example FIDDLE
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 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>
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;