im a student, not too experienced with coding. trying to make a software solution for my class, and having some problems with running <%...%> tags inside functions that are in tags in an ejs HTML file.
<script>
//grab elements
const textBox = document.querySelector(".lineBox");
const nextLine = document.querySelector(".nextLine");
const prompt = document.querySelector(".question");
//display starting script line
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
//nextline function
function updateLine() {
<% counter = counter + 1; %>
if ("<%= JSON.stringify(scripts[scriptName][counter][0]) %>" == 1) {
<% counter = counter + 1; %>
}
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
}
//prompt line function
function promptLine() {
<% counter = counter + 1; %>
textBox.innerHTML = "<%= JSON.stringify(scripts[scriptName][counter][0]) %>";
}
//call functions onclick
nextLine.onclick = updateLine;
prompt.onclick = promptLine;
</script>
I am currently making a website that displays lines off a script for actors to learn. The problem is that the scriptlet tags are running regardless of the functions. My first thought was to put the whole function inside scriptlet tags, but unfortunately that means that I cant use the variables from the frontend ejs file like textBox and prompt inside those tags because that runs in the server side.
I don't have a lot of knowledge about this so I'm sure I'm wrong on something here. Any tips?
Related
I'm loading some of data to a list called "TransactionNames" in the code behind of the master page (TestMaster.Master).
Now I need to pass that list of data to front-end of the master page(TestMaster.Master) using java script.
I tried like above,
If you have a List in code behind that is declared outside a method:
public List<string> TransactionNames = new List<string>();
Then you need to create an array in javascript:
<script type="text/javascript">
var TransactionNames = ["<%= string.Join("\",\"", TransactionNames) %>"];
//or
var TransactionNames = <%= "['" + string.Join("','", TransactionNames) + "']" %>;
for (var i = 0; i < TransactionNames.length; i++) {
alert(TransactionNames[i]);
}
</script>
Or it becomes even easier when you use Newtonsoft.Json to serialize objects:
var TransactionNames = <%= Newtonsoft.Json.JsonConvert.SerializeObject(TransactionNames) %>;
You didn't mention exactly what do you want to do with the transaction names on the front-end of master page e.g. adding them to a menu, concatenating them to a label etc or creating a structure from the names;
Suppose you want to create a structure; here is the code
for(i =0;i< TransactionNames.length;i++)
{
$("#ul").append("<li>" + TransactionNames[i] + "</li>");
}
You can do using declare global public variable:
Code Behind:
public string[] TransactionNames=new string[]
{
"schnauzer",
"shih tzu",
"shar pei",
"russian spaniel"
};
Source File:
<script type="text/javascript">
var TransactionNames= <%= TransactionNames %>;
for(var i=0; i < TransactionNames.length;i++){
var tx=TransactionNames[i];
}
</script>
I have a JavaScript function that I wrote and embedded in an .aspx page. I declared variables at the top of the function that access ConfigurationManager.AppSettings and also the sessionState tag as follows:
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
This function has been working just fine. I've realized that I will need to use the function across four other pages so I decided to move it to an external JavaScript file. According to this question and accepted answer...
Accessing ConfigurationManager.AppSettings in Java script
...external JavaScript files do not evaluate code inside of these "server-side code" tags, therefore, values from the web.config file must be passed from the .aspx page as parameters. I moved the function to an external JavaScript file and call the function like this:
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
externalFunction(Value1, Value2)
</script>
The external JavaScript functions begins as follows:
function externalFunction(Value1_, Value2_) {
debugger;
var Value1 = Value_1;
var Value2 = Value_2;
...
}
As I debug the JavaScript function, the arguments themselves are undefined. What am I missing here?
Update - 4/12/17
I have tried calling the function in both of the following ways.
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "1";
var Value2 = "2";
externalFunction(Value1, Value2);
</script>
<script src="Scripts/JavaScript.js" type="text/javascript">
var Value1 = "1";
var Value2 = "2";
</script>
<script src="Scripts/JavaScript.js" type="text/javascript">
externalFunction(Value1, Value2);
</script>
Using IE's debugger, I can see that the values were pulled correctly from the web.config file, but the function still is not being called. I'm stumped.
Try with two separate script tags, and see any different.
<script src="Scripts/JavaScript.js"></script>
<script type="text/javascript">
var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";
externalFunction(Value1, Value2);
</script>
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.
When i call my function in my js.erb template it replaces the entire page rather than just the div that i indicate. Can anyone help?
remove.js.erb
$('div.mini-basket-wrapper').html("<%= j(render 'shop/baskorder/mini_basket') %>");
#This replaces the page completely
$('#basket-info').load(document.write(basket_text()));
view
<div id="basket-info">
<div id="basket-amount">
<div class='mini-basket-icon'>
<%= image_tag 'shop/icons/basket.svg', alt: '' %>
</div>
<script type='text/javascript'>
document.write(basket_text());
</script>
</div>
</div>
JS
function fc_basket_text_from_cookie(empty_text, normal_text)
{
var basket = readCookie('bk');
if (basket)
{
var parts = decodeURIComponent(basket.replace(/\+/g, '%20')).split('|')
if (parseInt(parts[1]) == 0)
return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
// return empty_text
else
return normal_text.replace(/##VALUE##/g, parts[0]).replace(/##ITEMS##/g, parseInt(parts[1]));
} else {
return '';
}
}
var emptyBasketHTML = "<span class='header_text'>Items in basket: 0 Total: £0.00</span>";
function basket_text(){
var populated = "<span class='header_text'>Items in basket: ##ITEMS##</span><span class='header_text'>Total: ##VALUE##</span>";
//populated += "<input type='submit' value='Checkout' name='commit' class='go_botton header-checkout-button'>"
return fc_basket_text_from_cookie(emptyBasketHTML,populated);
}
Reading here: Using document.write.
When the page finishes loading, the document becomes closed. An attempt to document.write in it will cause the contents to be erased.
Further the .load() function is used to load data from a server. I believe you want the .html function.
[Untested] Change the line $('#basket-info').load(document.write(basket_text()));
To $('#basket-info').html(basket_text());
Thanks for all the input. Realised what i was doing wrong and decided to add an ajax on success to my js file:
$(document).on('ajaxSuccess', function(){
$('#basket-amount-info').html(basket_text());
});
Added this id #basket-amount-info to contain the script in the view.
I'm trying to assign a javascript variable data from ror. I already made the query, and it gives me what i want (a single integer), but i can't assign it to a js variable. Here is the js script i'm using:
<script type="text/javascript">
$(function() {
var number_of_products = '<%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>';
$(document).ready(function(){
for (i=1; i <=number_of_products; i++) $('#itemsAmount').append('<img src="images/box.svg"/>');
})
})
</script>
But i can't seem to pass the ror value (<%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>) to the js variable (number_of_products)
Any ideas?
Thanks,
Shai.
It would seem your problem isn't with getting the value into javascript, its simply the wrong type try and change your code to the following
<script type="text/javascript">
$(function() {
var number_of_products = <%= Post.where(:id => 1).select(:amount).pluck(:amount)[0] %>;
$(document).ready(function(){
for (i=1; i <=number_of_products; i++) $('#itemsAmount').append('<img src="images/box.svg"/>');
})
})
</script>
Edit:
Do you have #itemsAmount on your page?
Working fiddle http://jsfiddle.net/DeMd2/