I am trying to use C# in javascript like we are using it in MVC Razor View using # sign,
like suppose an array name list is passed to the View so we can access it in View like:
View
Length of array : <input type="text" value="#Model.list.Length" />
Or we can iterate list array also like:
#for(int i=0; i< Model.list.Length; i++)
{
console.log(Model.list[i]);
}
But my question is how we can iterate or use this array in the javascript code , something similar to :
JS
for(var i=0; i<#Model.list.Length; i++)
{
$("body").append("<h1></h1>").html(#Model.list[i]);
}
Thanks !
As i posted in my comment, this is a bit tricky. However, you can try to construct a javascript object with your c#.
Something like this (i don't know how this works exactly...):
var array = [
#for(var i = 0; i < Model.list.Length-1; i++){ #Model.list[i] , }
#Model.list[length]
]
which should result in:
var array = [
val1,
val2,
val3,
valn
]
Now you have an js var array, you can work with in your entire document.
You can't do it exactly that way. What you can do is use the C# to generate the javascript code for each line like this:
//...javascript code...
#for(var i = 0; i < Model.list.Length; i++)
{
$("body").append("<h1></h1>").html('#(Model.list[i])');
}
//...more javascript code...
This should output like this:
//...javascript code...
$("body").append("<h1></h1>").html(listitem0);
$("body").append("<h1></h1>").html(listitem1);
$("body").append("<h1></h1>").html(listitem2);
//etc.
//...more javascript code...
Related
I have a python list generated by my views.py in Django, and I would like to pass it to javascript in my HTML template.
I cannot seem to get it into javscript as an array... I need to evaluate if the list/array contains certain numbers, but it is coming over as a string.
I am passing the list to my HTML template like this:
def get_context_data(self, **kwargs):
context = super(dashboardView, self).get_context_data(**kwargs)
mylist = [10,22,33,45]
context['mylist'] = mylist
return context
When I use:
<h1 id = "list"> {{mylist}}</h1>
it shows up on the browser as
it shows up as [10,22,33,45]
Then in my template I am using javascript I have:
var mylist = document.getElementById("list").innerHTML;
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
this returns in the console:
'
[
1
0
,
2
2
........
I want:
10
22
33
45
I have tried to convert to JSON in python, and parse it in javascript, but can't seem to convert this string to an array, or keep getting errors.
Any ideas for the best method here?
If you are absolutely certain your list is safe, (by that I mean it never, ever includes anything entered by a user), it is very simple.
In your view:
context={"my_list": ["item1", "item2"]}
In your template:
{{ my_list|safe }}
Renders as:
['item1', 'item2']
For example:
{{ my_list|safe }}.forEach(item => {
console.log(item)
})
Impressively, if you pass a string with an apostrophe, Django automatically changes the quote types, so
context = {"my_list": ["item1", "it'em2"]}
renders as (note the double-quotes):
['item1', "it'em2"]
so
{{ my_list|safe }}.forEach
still works (tested on Django 3.2.6).
Even this works:
context = {"my_list": ["item1", "it'em\"2"]}
renders as:
['item1', 'it\'em"2']
so
{{ my_list|safe }}.forEach
still works.
However, as I said at the top, if your list might include input from a user, I still wouldn't trust this approach.
In views you can make your object as a JSON object:
import json
mylistraw = [10,22,33,45]
mylist = json.dumps(mylistraw)
context = {''mylistjson': mylist}
Now you can use your object in JavaScript:
var mylist = JSON.parse("{{mylistjson}}")
Django has the json_script template tag that addresses XSS vulnerabilities by escaping the <, >, and & characters.
Django json_script docs here
You can simply use tojson tag to convert python list to js array.
It will be like -
var mylist = {{mylist|tojson}};
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Try it and let me know if any problem occurs.
In your case, a simple way is to send the list as string ','.join(mylist). And then in your templates, you could simply use split(',') in js.
views
mylist = [10,22,33,45]
context['mylist'] = ','.join([str(i) for i in mylist])
html & js
var mylist = document.getElementById("list").innerHTML;
mylist = mylist.split(',')
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Or in case your js is in the template as well
var mylist = '{{mylist}}'.split(',');
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
Set the list value in JavaScript and not HTML.
<script>
var mylist = {{mylist}};
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};
<\ script>
You need to do this in your HTML template file and not in an external JS file.
My div class array looks like this
[ <div class="divtitle" style="height: 22px;">A</div> ,
<div class="divtitle" style="height: 22px;">W</div> ,
<div class="divtitle" style="height: 22px;">E</div> ,
<div class="divtitle" style="height: 22px;">AA</div> ]
I have this javascript function
var products= document.getElementsByClassName("divtitle")[0].innerHTML;
return products;
But now i have more than 1 product name in the div and i am wondering how to write loop in JavaScript using this function.
var products= document.getElementsByClassName("divtitle").innerHTML;
var arrayLength = products.length;
for (var i = 0; i < arrayLength; i++) {
return products[i];
}
Can you please tell me what is wrong here?
Thanks
Assuming your div innerHTML looks something like this "product1, product2, product3.." when you get it products will be a string, and not a list.
When you loop over string length you actually loop over its characters.
Try to do something like this:
var products= document.getElementsByClassName("divtitle").innerHTML;
return products.split(",")
If you separate different products with comma, this should return a list of products.
PS. your question is a little unclear, it would help a lot if you show an example of the html elements, eg how divtitle looks like.
You're returning the entire product array within your for loop. you need to write something like this:
var products= document.getElementsByClassName("divtitle").innerHTML;
for (var i = 0; i < products.length; i++) {
/*you will write your code that you want to do with each product here
using the i index, such as: */
console.log(products[i])
}
I have a array that has IDs in JavaScript:
["1649545","1649546","1649547"] etc.
And I want to print the values of this array in a URL, so something like this the foreach function of PHP does;
foreach
www.google.com/[valueofarray]
end
I know the solution could be very easy, but I just cannot manage to find it.
I made a fiddle and used a for loop this is without the use of jQuery but only javascript. I made an example array called myArray, I used .length so that javascript stops when he's been through all of the strings in the example array.
var myArray = ['12345', '123456', '1234567'];
for (var i = 0; i < myArray.length; i++) {
console.log('http://foo.com/' + myArray[i]);
// alert(myArray[i]);
}
See it work (and be sure to open your browsers console or use alert instead for viewing the output)
jsFiddle
var p='http:',a=["1649545","1649546","1649547"],u='www.google.com';for(i=0; i<a.length; ++i) console.log([p,'',u,a[i]].join('/'));
Try this:
var idArray = ["1649545","1649546","1649547"];
var url = "www.google.com/";
idArray.forEach(function(id){
console.log("http://" + url + id);
});
https://jsfiddle.net/tcmn2Lda/
can anyone help me with javascript button who make PUT operation.
action : function() {
var selectedRecords = this.view.viewGrid.getSelectedRecords();
var lengthAr = selectedRecords.length;
for (var i=0; i < lengthAr ; i++){
alert(selectedRecords[i].id);
}
},
i want to update one column for all selectedRecords[all]. For this i must make PUT query like this:
http://wiki.openbravo.com/wiki/JSON_REST_Web_Services :
{data: {"_identifier":"United States","_entityName":"Country","$ref":"Country\/100","id":"100","client":
{"_identifier":"System","_entityName":"ADClient","$ref":"ADClient\/0","id":"0","active":true},"organization":
{"_identifier":"*","_entityName":"Organization","$ref":"Organization
... truncated for clarity ...
(USA)","_entityName":"ADLanguage","$ref":"ADLanguage\/192","id":"192","active":true},"currency":{"_identifier":
"USD","_entityName":"Currency","$ref":"Currency\/100","id":"100","active":true},"iBANLength":null,"iBANCode":null}}
but i'm new with javascript and i don't know how to do this. I can't undenstand this code:
What is _identifier? should not it be ID from selectedRecords[i].id?
How i can write the query in javascript?
I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/