passing javascript array to jquery - javascript

I've a javascript array and I want to iterate them with jstl for each and display the output.
<script type="text/javascript">
phoneFilterObject = {
allPhoneArray: []
}
var specPhone = [];
OnUserSelect(){
//loop through allPhoneArray
//do filtering logic and populate specPhone array
}
</script>
<body>
// here I want to iterate through the specPhone array and display it. also I want to populate hidden variables with values from specPhoneArray
// i want to do the following
<c:if test="${!empty specPhoneArray}">
<c:foreach items="${specPhoneArray}" var="phoneObj">
<c:out value="${phoneObj.name}"/>
<input type="hidden" name="phoneID" value="<c:out value='${phoneObj.id}'/>"/>
</c:foreach>
</c:if>
</body>
i'm not able to read javascript array in jquery. I tried the following
specPhoneArray = $(specPhoneArray); &
specPhoneArray = ${specPhoneArray};
this.specPhoneArray = $(specPhoneArray);
any help is appreciated.

You can't do that with JSTL but you can accomplish it by staying in JavaScript world. First create a template and add it to your page:
<script id="phone-tmpl" type="text/html">
{name}
<input type="hidden" name="phoneID" value="{id}"/>
</script>
then in JavaScript add a little template helper:
function t(s,d) {
for (var p in d) {
s = s.replace(new RegExp('{'+p+'}','g'), d[p]);
}
return s;
}
and then you can do (assuming you are using jQuery):
var phoneTmpl = $('#phone-tmpl').html(),
html = "";
for (var i = 0, l = specPhone.length; i < l; i++) {
html += t(phoneTmpl, specPhone[i]);
}
// do something with html
$('body').append(html);
You can also check this demo: http://jsfiddle.net/d5jaY/

Related

How to replace hidden input with global variable to hold data

Currently I save data in input type="hidden" and access them from any JS script using getDocumentById("sourceJson"). For example:
<input type="hidden" id="sourceJson" name="sourceJson" >
var val = document.getElementById("sourceJson").value
But it forces me to scatter many hidden inputs in the HTML file. What is good replacement to hold data and have access to it from all scripts? Some kind of global variables that can also be submitted to the server.
If you declare a variable in any normal script it should be available from any other script.
<html><body>
<script>
var varOne = "Hello ..";
</script>
<script>
var varTwo = ".. world";
</script>
<script>
alert(varOne + varTwo);
</script>
</body></html>
Update
To Store array data we can use localStorage.setItem("data", JSON.stringify(data));
const data = localStorage.getItem("data")? JSON.parse(localStorage.getItem("data")):[];
function setData(name, value){
data.push({"name":name, "value":value});
localStorage.setItem("data", JSON.stringify(data));
}
function getData(name){
var ret = undefined;
for(var x = 0; x < data.length; x++){
if(data[x].name == name){
ret = data[x].value;
}
}
return ret;
}

Using a javascript variable inside C# block

i am trying to get a variable by javascript and using it in my C# block but it looks like impossible.
this is my HTML:
<select class="form-control" id="Category">
#foreach (var item in Model.Categori)
{
<option value="#item.CategoriId">#item.CategoriName</option>
}
</select>
<div id="Container"></div>
and this is my javascript code:
$('#Category').on('change', function (e) {
$("#Container").append(`#foreach (var item in Model.YetkinlikKategorileri.Where(x => x.Id == $('#Category').val()))
{
<p>hello</p>
}`);
});
well is it possible to do something like that ? if not is there another way ?
You need something like this:
<script>
var data = [
#foreach (var item in dataList)
{
#Html.Raw("'"+item+"',")
}
];
$('#Category').on('change', function (e) {
var lst = data.find(/*Your condition*/);
for (var i = 0; i < lst.length; i++) {
$("#Content").append("<p>hello</p>" + data[i] + "<br/>");
}
};
</script>
dataList is the data which comes from server.
But in this way, you should get all data from server and put it into javascript data array. Then you should make lst by finding in data array.
But using ajax is better than this razor code.

Javascript Arrays and variable click functions

So I have set up two javascript arrays to pull information from some php. One array gets the name of the category to be clicked on, while the other array stores the class and id tag for the category. The class and id tags are the same other than there css type, but the array needs to output them into document elements and then, when clicked, affect the relevant areas of the document. I also need to remove duplicates from the arrays, which doesn't seem to work under my current code:
<script type="text/javascript">
var BookSeries = [];
var BookClass = [];
var i=0;
</script>
then variables for the array are pulled from php and output this way:
<script type="text/javascript">
var uniqueSeries = BookSeries.filter(function(elem, pos) {
return BookSeries.indexOf(elem) == pos;
});
var uniqueClass = BookClass.filter(function(elem, pos) {
return BookClass.indexOf(elem) == pos;
});
while (uniqueSeries[i]) {
document.write( "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>" );
i++;
}
for(var i = 0; i < uniqueClass.length; i++) {
$np("#"+uniqueClass[i]).click(function(){
$np(".postitem").fadeOut(200);
$np("."+uniqueClass[i]).fadeIn(200);
});
}
</script>
You are using jquery so you can do the following for appending the elements to the DOM:
var htmlString = "";
for (var i = 0; i < uniqueSeries.length; i++) {
htmlString += "<span id='"+uniqueClass[i]+"'>"+uniqueSeries[i]+"</span>";
}
$("#myContainer").html(htmlString);
Not sure what is $np so I'll assume you meant jquery's $.
for(var i = 0; i < uniqueClass.length; i++) {
var uClass = uniqueClass[i];
$("#" + uClass).click(function(){
$(".postitem").fadeOut(200);
$("." + uClass).fadeIn(200);
});
}
Edit:
"#myContainer" refers to the id of the dom element you want to append the html to. if you just want to append it to document you can do:
$(document).appendTo(htmlString);
Also see I updated the code above to reflect your comments about the uniqueClass array.

Accessing row element of table in Javascript

This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)

Input entry is not catched in Javascript

I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
But in this task, firstly I try to catch that input in javascript file, and I am failing in the same. Can you tell me for this, which command will I use ?
Till now my work is :-
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT FILE:-
function addString(x) {
var val = x.name.value;
//var s = document.getElementById("name_id").getElementValue;//x.name.value;
alert(val);
}
EDITED
My New JAVASCRIPT FILE IS :-
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the string, but unable to show on the web page.
See this fiddle: http://jsfiddle.net/MjyRt/
Javascript was almost right
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
alert(s);
}
Try to use jQuery (simpler)
function addString() {
var s = $('#name_id').val();//value of input;
$('#list').append(s+"<br/>");//list with entries
}
<div id='list'>
</div>

Categories

Resources