How to use model attribute of a JSP into javascript? - javascript

Controller:
List<SampleModel> data = service.getdata();
model.addAttribute("modeldata",data);
return "jsp";
Is there a way to easily access/use the model attribute of a jsp in a javascript function? I tried accessing it in a loop but there's no result.
Sample:
<script type="text/javascript">
$(document).ready(function() {
sampleFunction();
});
sampleFunction() {
for (i=0;i<=10;i++) {
console.log(${modeldata[i].sampledatapath});
}
}
</script>
Thanks!

You can use following:
<script type="text/javascript">
$(document).ready(function() {
sampleFunction();
});
function sampleFunction(){
<c:forEach var="model" items="${modeldata}">
console.log("${model.sampledatapath}");
</c:forEach>
}
</script>

Related

how to use javascript variable into array in laravel blade file

How to use var aid value assign into $data array? I am getting error: "Use of undefined constant aid". I am working on Laravel 5.4. I want to show ($data['services'][aid]->servicesubdetails) value in tage. My code is below:
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html('{{ ($data['services'][aid]->servicesubdetails) }}');
}
</script>
Single quotes are interrupted by another single quote.
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html(“{{ ($data['services'][aid]->servicesubdetails) }}”);
}
</script>
Notice “ instead of ‘.
EDIT
You can use json to use you PHP array in javascript
Look at LaravelDisplayData and PHPJsonEncode
<script language="JavaScript">
var data = #json($data)
function theFunction(e)
{
var aid= e.target.id;
$("p").html(data.services[aid].servicesubdetails);
}
</script>

Javascript Not Running in HTML

Given the following:
HTML
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<table>
<tr class='foo'><td>one</td></tr>
<tr class='foo'><td>two</td></tr>
<tr class='foo'><td>three</td></tr>
</table>
<script type="text/javascript" src="http://underscorejs.org/underscore.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javscript" src="https://gist.githubusercontent.com/anonymous/d25940992da18e05f3f2d50889f6a4c2/raw/f013565c33d17abb33a4f5ad7717aae090873516/test.js"></script>
</body>
</html>
JS
// Generated by CoffeeScript 1.10.0
(function() {
var hasChildren, rowsWithChildren;
$(function() {
return console.log('starting');
});
$(function() {
var filtered, rows;
console.log('here');
rows = $('tr');
filtered = rowsWithChildren(rows);
return console.log(filtered);
});
rowsWithChildren = function(rows) {
return _.filter(rows, function(r) {
return hasChildren(r);
});
};
hasChildren = function(row) {
return row.children().length === 1;
};
}).call(this);
When I open that HTML page in my Chrome Browser, I see the table on the screen. But, I don't see any console.log ... statements in the output of the Developer Tools Console.
Also, when I look at Dev Tool's Sources, I don't see the JS from gist.github.com....
What's wrong with this HTML?
There's two problems with what you're attempting to do:
There's a typo on the line where you link to the Gist - should be text/javascript not text/javscript.
Github doesn't allow you to hotlink to code/assets hosted on their website - essentially you can't use them as a CDN. Here's a blog post from them explaining this in more detail.
The third script element has a wrong type value. With a wrong value, the loaded file will not be interpreted as JavaScript.
So change:
<script type="text/javscript" ...
to:
<script type="text/javascript" ...
As I remember there is "onready" problem in this version of jQuery (I may be mistaken).
As for "text/javascript" it's unnecessary nowadays.
Try to merge your two $(function(){}) into one, and remove these "returns" inside them. Like this:
(function() {
var hasChildren, rowsWithChildren;
$(function() {
console.log('starting');
var filtered, rows;
console.log('here');
rows = $('tr');
filtered = rowsWithChildren(rows);
console.log(filtered);
});
rowsWithChildren = function(rows) {
return _.filter(rows, function(r) {
return hasChildren(r);
});
};
hasChildren = function(row) {
return row.children().length === 1;
};
}).call(this);
Hope it helps.

Calling JavaScript function in MVC 5 Razor view

I have seen in another post that you can call a JavaScript function in your razor code like so:
#:FunctionName()
For me though this only outputs the actual words FunctionName()
Here is my view:
#model PriceCompare.Models.QuoteModel
#{
ViewBag.Title = "Quote";
}
<h2>Quote</h2>
#if (#Model.clarify == true)
{
// do drop down loic
#:ShowClarify();
}
else
{
// fill quote
#:ShowQuote();
}
<div class="clarify">
You can see the clarify div
</div>
<div class="quote">
You can see the quote div
</div>
#section head {
<script type="text/javascript">
$(document).ready(
function ShowQuote() {
$(".quote").show();
},
function ShowClarify() {
$(".clarify").show();
}
);
</script>
}
Is it because I have nested it in an `#if'? Anyway around this?
You need to put your javascript in a <script> tag, and you need to call the functions within their scope:
<script type="text/javascript">
$(document).ready(
function ShowQuote() {
$(".quote").show();
},
function ShowClarify() {
$(".clarify").show();
}
#if (#Model.clarify == true)
{
// do drop down loic
ShowClarify();
}
else
{
// fill quote
ShowQuote();
}
);
</script>
If you are passing any parameter to the JavaScript function, it must be enclosed with quotes ('').
foreach (var item in files)
{
<script type="text/javascript">
Attachment(**'#item.FileName'**, **'#item.Size'**);
</script>
}

Passing a parameter to my Knockout ViewModel

I have an MVC site that uses Knockout JS. Basically, the MVC handles routing to a few different pages, and each page has a viewmodel.
One of the pages requires a parameter to filter the data. The code for the MVC Controller for that page is as follows:
public ActionResult Transactions(int policyId)
{
ViewData["policyId"] = policyId;
return View();
}
The View for that page includes a hidden field.
<input type="hidden" name="hldPolicy" value="#ViewData["policyId"]">
Then after the html for the page,
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script>
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
var transactionViewModel = new TransactionViewModel(policyId);
ko.applyBindings(transactionViewModel);
});
</script>
}
The problem is this doesn't work because the hidden field is undefined when the script runs. That doesn't make sense to me as I thought that was what the $(document).ready was protecting against. What am I doing wrong here? And is there a better way to pass a parameter from the URL params into the viewmodel?
You can use it like this. Here you dont actually have to pass the parameter instead define a function which will be called on viewmodel initialization and get the data according to your requirements.
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(){
var policyId = $('#hldPolicy').val();
self.SomeProperty(policyId)
}
self.LoadData()
}
$(document).ready(function () {
ko.applyBindings(new TransactionViewModel());
});
</script>
}
When knockout model will be initialized it will call self.LoadData() automatically.
EDIT
I found you are missing id attribute at your input
<input type="hidden" id="hldPolicy" name="hldPolicy" value="#ViewData["policyId"]">
Now it should work properly.
EDIT:
You can also do it like this
#section scripts
{
#Scripts.Render("~/bundles/myBundle")
<script type="text/javascript">
function TransactionViewModel(policyId){
var self = this
self.SomeProperty = ko.observable()
self.LoadData = function(policyId){
self.SomeProperty(policyId)
}
self.LoadData(policyId);
}
$(document).ready(function () {
var policyId = $('#hldPolicy').val();
ko.applyBindings(new TransactionViewModel(policyId));
});
</script>
}

How to get JSON value from list on JQuery?

This is my example:
data.json=
{
'list':[{
'name':'first',
'rating':'50%',
'story':'Once upon a time'
},
{
'name':'second',
'rating':'65%',
'story':'New chapter'
}]
}
HTML code:
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('data.json', function(data){
var new_data=JSON.parse(data)
alert(new_data.list[1].name)
alert(new_data.list[1].rating)
alert(new_data.list[1].story)
});
});
</script>
Why this code doesn't work? I want to get: second, 65%, New chapter. Maybe you know how to solve this problem on native JS, without using JQuery? It would be great/
You should just remove the 'JSON.parse' statement. 'getJSON' already parses the data.
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('data.json', function(data){
alert(data.list[1].name);
alert(data.list[1].rating);
alert(data.list[1].story);
});
});
</script>

Categories

Resources