Passing Values from a JSP page to a javascript function - javascript

I have a jsp page that updates what is listed based on the selection in a box.
<form:select path="Value" id="select" onchange="update()" items="${Values}" />
And in another file the corresponding update function that populates based on what you selected and the item. This works for one box, but I need to have multiple boxes, but copying the code into a for loop generates multiple boxes, but the update function only points to the id of the object "select". I want to create a way to have select to be variable, so that it generates multiple objects with different values so that they don't point to the same thing.
My thought was to just create a var and then have it count, so that at id="select" can force it to create different objects... but the update function reads from the jsp with
var Val = $('#select option:selected').val();
In order to make them match, I need to pass parameters into the update() function, but when I fill in update method with parameters, the JSP can no longer call it. I tried
Update(var n) { //code here}
and
Update(int n) {//Code here}
But when the JSP statement runs update(//ValueIwant), it always throws the error of not finding the method.
So my question is , how can I pass a parameter from a jsp page to the javascript function dynamically without hardcoding all the values.

i figured it out. It's pretty simple. Just call the function(Parameters) from JSP, but in the javascript, the method is just declared with the parameter not having a type.
Function Myfunction (N)
{
//code
}

In this specific situation, the javascript keyword this can be used to pass along the reference of the element.
Staying as close as possible with provided code (including jQuery use), this would be:
<form:select path="Value" id="select" onchange="update(this)" items="${Values}" />
<!-- 3 more times; id should be changed and kept unique -->
<!-- ... -->
<script type="text/javascript">
function update(srcElement) {
var Val = $(srcElement).find('option:selected').val();
// want to make sure it's OK so far?
console.log(Val);
}
</script>
Now, in the general case, as others have mentioned, it's essentially a question of how you use the JSP tags so as to generate HTML (and here embedded javascript) that does what you want it to do.
I haven't practiced Spring MVC (I assume that's what is being used here), but in pseudo-code, this could look like:
<!-- remember? this is *pseudo-code*,
for I ignore the form:select capabilities,
specifically towards runtime expressions like ${i}
-->
<% for(int i= 0; i<4 ; i++) { %>
<%-- maybe the following line is not 100% OK;
fix it according to your taglib documentation --%>
<form:select path="Value" id="select${i}"
onchange="update(${i})" items="${Values}" />
<% } %>
<script type="text/javascript">
function update(index) {
var Val = $('#select' + index + ' option:selected').val();
// want to make sure it's OK so far?
console.log(Val);
}
</script>

Related

Is it possible to declare Javascript function variables in html?

Sorry, I am just very new in this and had a previous experience in C++, and the question is it possible to do in javascript/html.
I want to make a function in JavaScript which replaces image on click using an array of image locations. Is it possible somehow to declare the needed variable (position number in the array) in the html? So I don't have to create a separate function for each individual image.
In the c++ you make a function and then declare a variable inside the brackets. Is it possible here, and if not, is there any close solution?
JavaScript:
var imgArray = ["images/2.jpg","images/3.jpg"]
function newImage() {
document.getElementById('pic').src = imgArray[1];
}
HTML:
<div class="project" id="ba">
<p onclick="newImage()">Poster</p>
</div>
Is it possible to insert the number in html "newImage(NUMBER)"?
You can send the index number from HTML and receive that in the javascript function as a parameter:
function newImage(index) {
document.getElementById('pic').src = imgArray[index];
}
// in the html
<div class="project" id="ba">
<p onclick="newImage(1)">Poster</p>
</div>
If you plan on using only one <p>, you can initialize a counter variable which gets incremented every time you click on "poster" label and mod it to the length of the images array. It would loop the available images.
var imgArray = ["images/2.jpg","images/3.jpg"]
var counter = 0;
function newImage() {
document.getElementById('pic').src = imgArray[counter];
counter = ++counter % imgArray.length;
}
<div class="project" id="ba">
<p onclick="newImage()">Poster</p>
</div>
<img id="pic" src="#"/>
Else, update your newImage() function to have an argument newImage(index) and pass the needed index in your <p onclick="newImage(1)">poster</p>
You can't really declare variables in HTML. So it's impossible to do something like onclick="newImage(variable);", with exclusively HTML. If you're using a framework like ASP.NET you can do things like onclick="newImage(#variable);" using Razor. I believe Angular, React, etc. all provide similar functionality.
However, there are other ways to achieve something similar in a "vanilla" setup.
If it's just a static number you can pass it with no variable. Something like onclick="newImage(3);"
You can also set a value attribute which can be accessed in JavaScript as well. something like <p id="poster" value="3" onclick="newImage();">Poster</p>.
Then in JS:
function newImage(){
value = document.getElementById("poster").value;
/* do something with the value */
}
If you're using PHP you can also pass PHP variables to JavaScript through the onclick function as demonstrated here. I would recommend this route if you're dynamically generating your HTML (e.g. within a PHP loop) and might not want to hard code each individual value.

Update some fields on change and on load

We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.

call JavaScript function inside razor foreach statement

I have looked through several posts but have not found an answer that actually solves this issue so I am asking whilst trying to provide the most pertinent details.
I have a very simple script file called custom.js ...
function AddListItemToUnorderedList(pageCode, menuName) {
$('.child_nav').append('<li><span>' + menuName + '</span></li>');
}
I have made reference to that script in my partial page.
<script type="text/javascript" src="~/Scripts/custom.js"></script>
#{
Layout = null;
}
<ul class="child_nav" style="display: none;"></ul>
#foreach (var item in ViewBag.MenuItems)
{
#Html.Raw("<script type='text/javascript'>")
#Html.Raw("AddListItemToUnorderedList('")
#item.PageCode
#Html.Raw("', '")
#item.MenuName
#Html.Raw("');")
#Html.Raw("</script>")
}
The above code works but it looks terrible AND it adds a script tag to the markup for each item in the MenuItems collection. The MenuItems collection simply contains a list of two strings correlating to my menu's display name and html link....consider this to be populated with something as simple as Test Page for the name and myTestPage.com for the link.
I have see some shortcut syntax like this
#: AddListItemToUnorderedList(item.PageCode, item.MenuName)
however, I am not able to get that to work no matter what I try.
Any clear suggestions that work that will allow me to make a direct call to the JavaScript function passing in the two properties from the ViewBag where I don't have to create the script tags and use #Html.Raw?
Something like the below should work. Pull out the script tags from the foreach, and then reference the javascript. You'll also have to put <text></text> tags around the javascript and quotes around the variables so they will transfer correctly:
<script type='text/javascript'>
#foreach (var item in ViewBag.MenuItems)
{
<text>AddListItemToUnorderedList('#item.PageCode', '#item.MenuName')</text>
}
</script>

many javascripts tags inside asp page makes performance low

I have an asp.net 4.5 (C#) page on VS2013. In this page, I am using a loop to itrate threw some of my objects. for each object(product) I have a textbox (input with type=textbox) which I use jquery on to make it a spinner .
I need this inside the loop for every product since I want each spinner to have it's parameters from the object (min, max, step size, is decimal etc.).
The loop goes something like that:
foreach ( Product product in getCart().ItemsList() ) {
String spinnerId = "spinner_" + product.Code;%>
<input id="<%:spinnerId %>" name="<%:product.Code%>">
<script type="text/javascript" language="javascript">
setSpinner('<%:spinnerId%>','<%:product.min%>','<%:product.max%>','<%product.step%>');
</script>
<%}%>
and in the head of the page I have:
function setSpinner(id,minVal,maxVal,stepVal){
j("#"+id).spinner({
min: minVal,
max: maxVal,
step: stepVal,
});
}
The problem is, that when I have the loop goes over a few times (10-15) the page loads very purley and the "onready" functions are taking a few seconds to perform, which meaning some fields that needs to be hidden are shown for 2 seconds and only than disaperas (this includes ajaxcontroltoolkit controls such as popupextender panel etc.).
To make this simple, the javascript code itself makes no matter.
If you try something like this:
<%for (int i=0;i<100;i++){%>
<script type="text/javascript" lang="javascript">
</script>
<%}%>
The same problem occures.
It seemes that even an empty javascript block is making the page take a long time to complete, if youe use it multiple times.
Why are 50\100 empty javascript blocks making the page lag so bad? and what can I do to solve this, considering I have to use the javascript code with each of the my objects data?
Try adding the info you need in data- HTML attributes, and calling javascript one single time. Something like
foreach ( Product product in getCart().ItemsList() ) {
String spinnerId = "spinner_" + product.Code;%>
<input id="<%:spinnerId %>" class="spinner" name="<%:product.Code%>" data-min="<%:product.min%>" data-max="<%:product.max%>" data-step="<%:product.step%>">
<%}%>
Then iterate on the "spinner" class inputs with jQuery:
$("input.spinner").each(function(intput){
$(this).spinner({
min: $(this).data('min'),
max: $(this).data('max'),
step: $(this).data('step'),
});
});
look at #David's ans first that surely is a better approach
as cleared by #roland this is ugly.
even if you need to inject js into the web page. inject a js object preferably and array containing all the objects and then inside a single block on page load iterate through it and get your work done.
var ps = getCart().ItemsList().Select(p=>new {
p.Id
/...All your propertiese.../
});
now inject ps inside the web page / script tag using any json library like Newtonsoft.Json.
var jsonString = JsonConvert.SerializeObject(ps);

Weird behaviour with change event in HTML

I have a struts tag like this
<s:select label="Select Item" name="select3ph3meter1" id="select3ph3meter1"
headerKey="0" headerValue="-- Please Select --" list="meterHeaderList"
required="true" onchange="show_3ph3meter1(this.value)" />
The problem is it is not calling the above function on change event. It works when I change the code to this:
... onchange="alert('calling')"
I can't understand what's happening here.
Here is the JavaScript function:
function show_3ph3meter1(select3ph3meter1) {
$("#3ph3meter1").load("meterFiller3p31.action",{select3ph3meter1:select3ph3meter1});
}
function show_depotReceipts(selectrecitem) {
$("#recQuantity").load("depotRecQ.action",{selectrecitem:selectrecitem});
$("#recRange").load("depotRecRange.action",{selectrecitem:selectrecitem});
}
The adjacent function is working perfectly so I assume there is no JavaScript error.
Also, when I put in another function (for instance the adjacent function name in onchange), it is also working. The problem may be with this particular function name show_3ph3meter1().
Hi if you have some other java script written over there contains errors , this code wont work.
So better have like this
<select class="style" onchange="//do something like this
//var e = document.getElementById('selectelement'); //if (e) e.value=100;" />
please check in IE browsers to get the java script errors. write entire code in that change event
First check your calling function name
if this is correct then just write
onchange="javascript : show_3ph3meter1(this)"
and get value on the function
3 else try the access value in function with selector
var elem = document.getElementById("short_code"),
selectedNode = elem.options[elem.selectedIndex];
var valu = selectedNode.value;

Categories

Resources