How to loop in a js that lie in a jsp page - javascript

I have a jsp page wherein I've used javascript function and I'm calling this using onClick present inside a form:
<script type="text/javascript">
function fa(){
<%
String as = null;
int aa =10;
for(int q =0; q<=aa ; q++){
if(q==5){
as="asds";
}
}
%>
<%= as%>
}
</script>
I'm a little confused about using javascript in a jsp page. How do I use the for loop? Usually, for loop can be called directly inside a js but since this is a jsp page, how will I use it? Do I have to call forEach instead? Right now, this code does not work.

You can use the for loop of JavaScript itself.
<script type="text/javascript">
function fa(){
var as = null;
var aa =10;
for(var q =0; q<=(Number)aa ; q++){
if((Number)q==(Number)5){
as="asds";
}
}
alert(as);
}
</script>

Related

Can We Append (Chunk of) HTML in jQuery using Html.Partial Helper? C# ASP.Net MVC 5

As the title suggests, I have a chunk of HTML which I put in one of my PartialView:
<div id="meaningPart">
#Html.Partial("_Meaning", new MeaningModel() {number = 1})
</div>
where my _Meaning partial View looks like this:
<div class="chunk">
<!--a lot of html here-->
</div>
Then, I create a jQuery which respond to a <input type="number"/> event (up and down) like the following:
<input id="numberMeaning" type="number" class = "col-md-2 form-control form-control-plus number-input" min = "0" max = "99" value = "1"/>
$(document).ready(function () {
var iCnt = 0;
$("#numberMeaning").on('change', function () {
var num = parseInt($("#numberMeaning").val());
if (num > iCnt) { //up
iCnt++;
$("#meaningPart").append("<p>ok dude, this is really a new item!</p>");
} else { //down
iCnt--;
}
});
});
now, the above code works fine because I simply put "<p>ok dude, this is really a new item!</p>" in the jQuery append, but if I change this part:
$("#meaningPart").append("<p>ok dude, this is really a new item!</p>");
Into
$("#meaningPart").append("#Html.Partial("_Meaning", new MeaningModel() {number = 2})"); //by right, the number should follow iCnt here.
Then, although the razor engine shows that the syntax is correct, the new Partial HTML just doesn't render.
How do we create a new partial HTML using jQuery? Is that possible?
(I am not too familiar with template attribute or jQuery.clone - but if it anyone can show how the adding to the html element can be done using those, I am open to that too)
try it like below
$(document).ready(function () {
var iCnt = 0;
$("#numberMeaning").on('change', function () {
var num = parseInt($("#numberMeaning").val());
if (num > iCnt) { //up
iCnt++;
// your GET /Controller/Action should return "partial HTML" based on iCnt
$("#meaningPart").append($('<div>').load("/Controller/Action?iCnt=" + iCnt));
} else { //down
iCnt--;
}
});
});
your Action in Controller like
public ActionResult Action(int iCnt)
{
//get model based on 'iCnt'
var model = GetModel(iCnt);
return PartialView("~/views/Folder/partialview.cshtml", model);
}
You can use $('#selector').html(content) where content is your template. I cannot imagine to create a partial view using jquery
Short answer: No.
Please be aware of the difference between
JavaScript (Jquery) and
MVC/ASP.Net (Razor).
JavaScript is executed on the client site in the browser.
MVC is executed on the server.
So the server is reading the razor stuff and creating a valid HTML page from it.
This is delivered to the browser.
The browser is creating something the user can see and then is executing the JavaScript.
So what you are doing in your example is trying to get JavaScript to execute a Razor function.
The only way to do something like that would be to use AJAX.
You can do it.
First you need to put the chunk of your partial html to a js var inside your main .cshtml file.
<script>
var chunkHtml = "#Html.Partial("_Meaning", new MeaningModel() {number = 2})"
</script>
and then do your append in your javascript file.
$("#meaningPart").append(chunkHtml);

Change a string of two html files from javaScript

I have a list in one file html called "filed1":
<ul>
<li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br>
<FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>
Now I want to change a string in other html "filed2":
<a id="logo-header2">
<h1>
<span class="site-name" id="element">Details</span><br>
</h1>
</a>
Using Java Script:
function move() {
mywindow = window.open("file2.html");
mywindow.document.getElementById("element").innerHTML="Changed");
}
But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?
The problem is that you are trying to retrieve the DOM element before the window is loaded.
Try following
mywindow.onload = function() {
mywindow.document.getElementById("element").innerHTML="Changed";
}
Like #nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.
Another approach you can try is perhaps passing the string as a variable in the url, like so:
function move(){
window.open("file2.html?str=Changed");
}
And then in file2.html, try something that runs on page load:
window.onload = function(){
var str = $_GET('str');
document.getElementById("element").innerHTML = str;
};
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.

How to handle arraylist in javascript function.?

I am passing arraylist object to javascript function on the click on button.below is my code. But I am unable to iterate that list in javascript.
<input type="button" onclick="viewSelectedOU('${quickLink.orgList}')" class="btn" value="view"/>
<script type="text/javascript">
function viewSelectedOU(selectedOU){
for(var i=0; i<selectedOU.length; i++){
var orgList1 = selectedOU[i];
}
}
</script>
can anyone tell me how to iterate java.util.ArrayList into javascript.?
check your rendered page, it shoud be something like onclick="viewSelectedOU([1,2,3,4])"
here is example of 2 calls:
http://jsfiddle.net/ybigus/K6CUm/
Test simple array
Test object array
Hope this helps
you can try
for(var i=0;i<selectedOU.all.length; i++){
var value = selectedOU.all(i);
}

Change asp variable in Javascript?

I'm editing a previous coworkers code so I don't know 100% how it works. It is written in Javascript and ASP. Here is the current code
<script>
var sessionDone = 0;
<% if session(ReturnSessionID()) = 1 then %>
sessionDone = 1;
<% endif %>
</script>
and then there is some html with links, like this:
<a href='#'>link</a>
What I want is this:
<script>
var sessionDone = 0;
var counter = 0;
$('a').click( function() {
sessionDone = 1;
if (counter == 3) {
<% session(ReturnSessionID()) = 1 %>
} else {
counter += 1;
}
});
</script>
When I do this, the line
<% session(ReturnSessionID()) = 1 %>
automatically gets run even if the if statement isn't true and even if I did not click a link. How do I make the link only get executed when counter is 3?
Note: I do not know ASP and I don't really need to learn it, this is the only time I will be using it.
ASP is being executed on the server. The resulting HTML/JavaScript is being sent to the browser and then there the JavaScript is being executed. You cannot mix it like this.
When you want client-side JS to update a server-side variable, you have to make a request from the client to the server, which tells the server to update the variable.

Is there a way to use a Ruby loop inside of HAML's :javascript region?

Inside of HAML, can we have a loop inside the :javascript region?
This will work:
- 10.upto(20) do |i|
:javascript
document.getElementById('aDiv').innerHTML += '#{i}';
and this will not:
:javascript
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
can the code above also be made to work as well?
%html
%head
:javascript
var foo = [];
#{
limit = rand(4)+3
array = (0..limit).to_a
array.map{ |i| "foo[#{i}] = #{rand(12)};" }.join ' '
}
console.log(foo.length);
%body
Running the above code gives this output:
<html>
<head>
<script type='text/javascript'>
//<![CDATA[
var foo = [];
foo[0] = 2; foo[1] = 0; foo[2] = 11; foo[3] = 8; foo[4] = 0; foo[5] = 1;
//]]>
</script>
<body></body>
</head>
</html>
As you can see, the big #{...} block (which may span multiple lines) runs arbitrary Ruby code. The result of the last expression (in this case the map{...}.join) is converted to a string and placed in the output.
Edit for Radek: If you want to declare a variable inside you Haml template, inside your JavaScript filter (which seems like an odd desire), then you need to be sure that the result of the block to_s doesn't produce unwanted output:
This Haml...
%p
:javascript
var foo = 12;
#{x = 42}
var bar = #{x};
...produces this HTML:
<p>
<script type='text/javascript'>
//<![CDATA[
var foo = 12;
42
var bar = 42;
//]]>
</script>
</p>
Whereas this Haml...
%p
:javascript
var foo = 12;
#{x = 42; ""}
var bar = #{x};
...produces this HTML...
<p>
<script type='text/javascript'>
//<![CDATA[
var foo = 12;
var bar = 42;
//]]>
</script>
</p>
But before you do this, ask yourself: why am I creating complex Ruby variables in my view?
Shouldn't this variable have been declared by my controller?
this one works
%script
- 10.upto(20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
Just wanted to add that the following gets you the type and CDATA, but without the funky behaviour of :javascript (I just had to implement something like this).
%script{ :type => 'text/javascript' }
\//<![CDATA[
- (10..20) do |i|
document.getElementById('aDiv').innerHTML += '#{i}';
\//]]>

Categories