Javascript: .value is undefined (involves NodeJs also) - javascript

So In my node I do an API and send it to my index.ejs page like
app.get("/", function (req, res) {
request("http://something/API", function (error, response, body){
if(!error && response.statusCode == 200) {
var result = JSON.parse(body) //Converts it into object
console.log(result)
res.render("home.ejs", {result:result});
}
})
})
Now In my Index Page, I do something like this
<% for ( var i= 0; i<result.length; i++ ) { %>
<table text-aling="left">
<tr>
<td> <%= i+1 %> </td>
<td> <p class="c"><%=result[i]["long"]%></p> (<%= result[i]["short"] %>) </td>
<td> <%= result[i]["price"] %> </td>
followed by a script just below body and head tag to do DOM manipulation.
<script type="text/javascript">
var x = document.getElementsByClassName("c")[1].value
console.log(x);
</script>
Now, Console.log(x) says undefined (while it does display result from API call on my frontend. Is it because it is an object? or what am I missing here? How can I get the value displayed on my frontend at my console.log

Your <p> does not have a value attribute. Use innerHTML:
x = document.getElementsByClassName("c")[1].innerHTML

I think the issue you are experiencing could be due to one of a few problems:
The placement of the tag
Make sure you place the script tag at the bottom of your html to ensure the above elements have fully rendered before the script is called. If the script runs before the elements with class "crypto" have loaded, the variable 'x' will be empty.
The number of elements with the class "crypto"
While I don't see any elements with class "crypto" in your example, you are trying to set variable 'x' to the element in the array at index 1 (the second position). If you have fewer than two elements with the class "crypto", trying to select index 1 will be undefined. If you're trying to select the first element with the class "crypto", use "var x = document.getElementsByClassName("crypto")[0].value" instead.
The presence of the class "crypto"
I see you list an element with the class "c", though none with the class "crypto". If you are trying to select the element with class "c", , use "var x = document.getElementsByClassName("c")[0].value" instead.

Related

Split string when comma is inserted and add it to a string array

I have an input that converts strings into 'styled tags' when the user types a comma, then, when the form is submitted, the strings are pushed into an array called 'content'.
On the EJS views, I am printing the result like <%= course.content %> but the result I am getting is 'string1,string2,string3,string4' and what I am after is that when is pushed into the array, each string must be a different element:
content ['string1','string2','string3','string4']
only then it will render properly in my views by looping the array. I want to achieve this by javaScript or jQuery only, please.
UPDATE: this is how I am rendering in my view
<ul>
<% var i; for (i = 0; i < course.content.length; i++) { %>
<li><i class="fas fa-check"></i> <%= course.content %></li>
<% }; %>
</ul>
UPDATE: this is my route where this POST request is being done
router.post("/", middleware.isLoggedIn, function(req, res) {
Course.create(req.body.course, function(err, course) {
if (err) {
req.flash("error", err.message);
return res.redirect("back");
}
res.redirect("/courses/" + course.id);
});
});
SOLVED! by using split on the server side like this:
router.post("/", middleware.isLoggedIn, function(req, res) {
Course.create(req.body.course, function(err, course) {
if (err) {
req.flash("error", err.message);
return res.redirect("back");
} else {
var content = req.body.course.content.toString().split(",");
course.content = content;
course.save();
console.log(course.content);
res.redirect("/courses/" + course.id);
}
});
});
Here is another solution in javaScript using function beforesubmit() by #garry man see below.
codepen
Long way
Otherwise there's one work around is as many tags you enter, that much input elements you should generate.
For e.g. my input tags are foo,bar then 2 input tags will be generated like
Note square brackets below
<input id="hiddenInput" type="hidden" name="course[content][]" required>
<input id="hiddenInput" type="hidden" name="course[content][]" required>
This is long way.
Another way
If you submit form via AJAX, then you can manipulate data before submitting and convert string into array with the use of .split(',').
Another way (Server side)
Split string by , on server side.
Okay so the problem is that you are submitting a form containing a single input which can only contain string values.
HTML Form practice is to have a single input for each array element to be posted, like:
<input name="course[content]"/> //value 1
<input name="course[content]"/> //value 2
<input name="course[content]"/> //value 3
So, in order to achieve that, before submit, you can call this function that generates those elements for you:
function beforesubmit(){
let submitVal = document.getElementById('hiddenInput');
let values = submitVal.value.split(',');
//let's get the container of the params passed to post
let paramsContainer = submitVal.parentElement;
// remove the param containting the string with commas as we're generating new ones
paramsContainer.removeChild(submitVal);
for(let i =0; i<values.length;i++){
//for each value, add a submit param containing each value
let tmp = document.createElement('input');
tmp.setAttribute('type','hidden');
tmp.setAttribute('name','course[content]');
tmp.setAttribute('value',values[i]);
paramsContainer.appendChild(tmp);
}
document.getElementsByTagName('form')[0].submit();
}
in order to call this function, replace your submit input with this:
<input type="button" value="submit" onclick="beforesubmit()">
Using this code you can already see the POST request difference between before and after. In your codepen it sends a single parameter, while with this snippet of code you are going to send an array of course['content'].
Now it's all up to how you are going retrieve data server side, you should be retrieving the course['content'] param as an array.

Accessing html elements from a div tree with javascript

I need to access title value from some img elements but these elements are deeply implemented in a div tree and after that into some tables.
Let me explain why I need them:
I use a portal where I have information regarding circuits from a network. This portal contains some locations with a few rows (2-3 usually -> circuits for that location). Each row starts with an img element and it can have a few values on title attribute. If the title value is != "No alarms" then I have to take all data from that row and I want to show them via a pop up notification on the bottom right corner near clock.
Below you have a screenshot for how are the html elements organized (for all locations).
http://imageshack.com/a/img661/962/ErjQOt.png
Below you have a screenshot for how is a location organized:
http://imageshack.com/a/img661/7453/QAP5oM.png
If title attribute == "Warning", for example, I have to take the data from the next td's in the same table. Each td has another div without id. Firsts 2 td's on each table have another element inside div: img on first one and a href on the second one.
I'm drawing the tree to show you exactly how are the html elements organized.
<table class="x-grid3-row-table">
<tbody>
<tr>
<td> <!--first td, this contains div->img-->
<div class="x-grid3-cell-inner x-grid3-col-0">
<img .... title="No alarms">
</div>
</td>
<td> <!--second td, this contains div->a href-->
<div class="x-grid3-cell-inner x-grid3-col-1">
<a href...>
</div>
</td>
<td> <!--3rd td, this contains div->string:Text1-->
<div class="x-grid3-cell-inner x-grid3-col-2">Text1</div>
</td>
<td> <!--4th td, this contains div->string:Text2-->
<div class="x-grid3-cell-inner x-grid3-col-2">Text2</div>
</td>
...
</tr>
</table>
Location-1 has 3 circuits, this means 3 tables. The above table is inserted in a div (div class="x-grid3-row x-grid3-row-first" from screenshot2). There are 2 more tables after this one on another div's (div class="x-grid3-row x-grid3-row-alt" & div class="x-grid3-row" from screenshot2) and I have to check the title attribute for each table.
Now my question is how to get the title attribute from each table on the same location? and if the title is != "No alarms" how can I get data from the next td's in that table?
Maybe I can use a loop for all 12 locations or maybe I can get them one by one. This is no big deal because there are only 12 locations but the nasty thing is inside each location to get info from each circuit.
I think there should be a syntax like this to reach each html elements and to get the right value.
var title = $('#ext-gen15-gp-location-1-bd table[0] td[0] img').attr('title');
var title = $('#ext-gen15-gp-location-1-bd table[0] td[1] div[0]').attr('innerHTML');
....
var title = $('#ext-gen15-gp-location-1-bd table[1] td[0] img').attr('title');
var title = $('#ext-gen15-gp-location-1-bd table[1] td[1] div[0]').attr('innerHTML');
...
var title = $('#ext-gen15-gp-location-9-bd table[0] td[0] img').attr('title');
var title = $('#ext-gen15-gp-location-9-bd table[0] td[1] div[0]').attr('innerHTML');
...
...and so on. I'm sure that this syntax is not correct but I think there should be a way to get that data.
I hope that now is explained better then the first time.
EDIT
Guys, thank you very much. You help me a lot. Your codes are working.
Anyway, I just want to ask you something else.
After 3 minutes the whole table is refreshing and I can't find a way to reload the function after that. When the content is refreshing, div ext-gen24 remains empty and after that is refilled with the content:
When is refreshing:
<div class="x-grid3-body" style="width: 1877px;" id="ext-gen24"></div>
After refresh is completed
<div class="x-grid3-body" style="width: 1877px;" id="ext-gen24">content</div>
Can you help me with a function you think it should work in this case ?
You'll need loop through multiple stages of the html: groups, tables, and columns:
var groups = $('.x-grid-group-body'); //hopefully all the '#ext-gen15-gp-location-X-bd' div have 'x-grid-group-body' as the class
groups.each(function () {
var tables = $(this).find('table');
tables.each(function () {
var columns = $(this).find('td');
var image = $(columns[0]).find('img');
var title = image.attr('title');
if (title !== 'No alarms') {
var allInnerHtml = '';
for (var i = 1; i < columns.length; i++) {
allInnerHtml += $(columns[i]).find('div').html() + '\n';
}
alert(allInnerHtml);
}
else {
//just to show that titles with 'No alarm' are skipped
alert('skipped');
}
});
});
See updated JSFiddle
Hope that helps! =)
If your Div tree has classes in the same format is now you can use something like this.
var title = $('.x-panel-bwrap').find('img').attr('title');
Or if the div class dependency is not confirmed, then assuming that img tag will always have a class name starting with 'tick', you can use this.
var title = $('img *[class^="tick"]').attr('title');
EDIT
Now that you have explained your problem more clearly, i've included a fiddle with the solution you need. Now you will have to expand it to suit your code more closely.
For example if you want to log each location separately, start looping through the locations first and then find tables inside them.
Basically you can use Jquery .find and .each to go through your comeplete html and do whetever you want.
var tableList = $('.x-grid3-row-table');
tableList.each(function() {
var imgTitle = $(this).find('img').attr('title');
alert(imgTitle);
if (imgTitle == 'Warning') {
infoTd = $(this).find('td:nth-child(3)');
text = infoTd.find('div').text();
alert(text);
}
});
FIDDLE

use jquery variable in # block razor

I'm strugling with a jquery script inside a cshtml page. For short my question is how to use a var inside a # statement in a cshtml page?
below an example of what I'm trying:
<select id="DefaultText">
<option value="-1">-- select --</option>
#foreach( var d in Model.DefaultTexts )
{
<option value="#d.Id" >#d.Name</option>
}
</select>
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
var text = #Model.DefaultTexts.First( t => t.Id == id );
$('#CustomProductText').val(text);
});
</script>
I can't reach the var id. It's out of scope. I've also tryed it with a for loop and a if statement. But in the if statement I get the same error: out of scope.
The full story is this:
On my page I've a dropdown list. The items to select are short names for default text parts. Based on the id or name, I want to show the default text part in a textbox.
#CustomProductText is my textbox where the content should be placed (code not posted).
I've also tryed it with #: and statement but that did not work.
What am I doing wrong or maybe its not even possible what I'm trying to do.
As an alternative I've added a action to my controller to get the text form there. Below the code:
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
$.post("Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
//$('#CustomProductText').val(text);
});
</script>
controller code:
[HttpPost]
public ActionResult GetDefaultText(int id)
{
using( var context = new MyContext() )
{
var text = context.DefaultText.First( d => d.Id == id ).Text;
return this.Content( text );
}
}
This doesn't work. The action doesn't get hit in debug mode.
regards,
Daniel
The $.post that is not working for you, you should prefix the url with / sign and it will be hit as expected:
$.post("/Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
As for the razor solution, you can't use javascript variables in the razor code as it's not a scripting language. What razor does is simply rendering the strings (be it html or javascript or anything) into the page.
To do what you want you either need to request the server to pass the text to your page or render all the texts you have in the page and then access this rendered content in your javascript.

difficulty getting list of values from series of input elements inside table rows

I'm completely stumped. Granted, in java script i'm like that kid trying to jam a square peg into a round hole.
My high level objective: The admins want the ability to edit text surrounding some text boxes, as well as the ability to add and remove 'paragraph'. The reporters and users want the values that are in the textboxes to be used in comparisons, etc (which is the original functionality).
My Solution: This project uses a pretty messy value - attribute table (called an EAV?), which now has fields with associated fields and is self referencing. I decided to leverage this to minimize changes to the database, so the admin essentially creates a string, denotes the places a text box belongs using '{}', and assigns a name to the attribute into text boxes that appear directly below the paragraph.
My Problem: Textboxes generate fine, as soon as the admin stops typing the "{}" count is checked client side, and the correct number of textboxes are added/removed in rows below. However, when the "change" mode (and thereby save the new string) I also want to save the attribute names they selected. I can't seem to get the actual value out of the input. The java script below sends null to elementList. Closer inspection indicates that var fieldNames is getting two elements of "undefined" so it makes sense that I'm getting null. Its also apparent that Its hitting something, becuase the number aligns with there being two 'nameField' rows.
DOM (Hemed down to the essentials)
<tr data-editMode="TextMode" data-ordinal="0">
....
<td>
<a class="changeMode">
<tr class="nameField">
<td colspan='4'>
<input type="text" value="Testing">
<tr class="nameField">
....
Javascript
function getAssociatedTr(row) {
var associatedRows = [];
associatedRows.push(row);
row = row.next('tr');
var hasAnother = true;
while (hasAnother == true) {
if (row != null && row.hasClass("nameField")) {
associatedRows.push(row);
row = row.next('tr');
} else {
hasAnother = false;
}
}
return associatedRows;
}
$(".changeMode").live("click", function () {
var options = $(this).data("options");
var theRow = $(this).closest('tr');
var rows = getAssociatedTr(theRow);
var fieldNames = new Array();
rows.splice(0, 1);
for (var index = 0; index < rows.length; index++) {
{
fieldNames.push(rows[index].next('.nameField').val());
}
}
$(".modal-header", c.rowsModal).html("<h3>Changing edit mode" + options.table + "</h3>");
c.rowsModal.modal("show");
$.ajax({
type: "POST",
traditional: true,
data: { "Name": options.table, "Ordinal": options.row, "EditMode": options.editMode, "ElementNames": fieldNames },
url: "/contracts/changeeditmode/" + c.id.val(),
success: function (data) {
theRow.replaceWith(data);
$.validator.unobtrusive.parse("#supplementForm");
c.rowsModal.modal("hide");
for (j = rows.length - 1 ; j >= 0; j--) {
rows[j].remove();
}
}
});
});
Server side
public ActionResult ChangeEditMode(long id, AddTrackedRowViewModel model,
string editMode, List<string> elementNames)
{
}
As a side note, I'm open to constructive criticism on the JavaScript.
EDIT
I have updated the line to
fieldNames.push(rows[index].nextAll('input').first().val());
But still getting undefined.
SOLUTION
fieldNames.push(rows[index].find("input[type=text]").val());
In this line:
fieldNames.push(rows[index].next('.nameField').val());
you are using the selector ".nameField", but this get a "tr" element, if you want the textbox you need this:
fieldNames.push(rows[index].next('.valid').val());
or using other selector that give you the textbox.

Array of object's index from request attribute in jsp and javascript

Is it possible to:
1
When I do:
$('#NContrato' ).val('${personList[0].NContrato}');
It works. But if I do
$('#NContrato' ).val('${personList[' + ind + '].NContrato}');
$('#NContrato' ).val('${personList[ind].NContrato}');
$('#NContrato' ).val('${personList[${ind}].NContrato}');
It doesn't and this is request.setAttribute(personList, ...) in a controller (I'm using spring MVC)
$('#NContrato' + ind) // JQuery $() ...It works but
${'${personList[' + ind ...} //Request ${} doesn't work concatenating string's
${personList[0].NContrato} // Works
Is there a way to do it?
2
I'd like to change
newPerson to have the clone of
${personList[0]}
I tried this ...
<script type="text/javascript">
function setNewPerson(ind) {
${newPerson=personList[0]};
}
</script>
but .... it gives this error:
org.apache.jasper.JasperException: /WEB-INF/pages/t4imovelZMAguaEdpGass.jsp(153,3) PWC6038:
"${newPerson=personList[0]}" contains invalid expression(s): javax.el.ELException:
Error Parsing: "${newPerson=personList[0]}"
EDIT:
JSP
<c:forEach items="${personList}" var="item" varStatus="status">
.....
<button type="button" onclick="change(${item.id},${status.count})"></button>
.....
</c:forEach>
.....
<form:form action="save()" method="post" modelAttribute="newPerson" id="personId" >
....
<form:input path="NContrato" id="NContrato" />
....
</form>
<script type="text/javascript">
function change(id, ind) {
$('#NContrato' ).val('${personList[0].NContrato}'); //Works
var ind=0;
$('#NContrato' ).val("${'personList[' + ind + '].NContrato'}"); // <- 1 Question
....
${newPerson=personList[0]}; // <- 2 Question
}
</script>
Controller (Servlet)
#RequestMapping(value="/saves*", method = RequestMethod.POST )
public #ResponseBody ModelAndView save(#ModelAttribute("newPerson") Person person,
BindingResult errors, HttpServletRequest request) throws Exception {
...
request.setAttribute("newPerson", subForm);
...
request.setAttribute("personList", personManager.getPersonList())
....
return new ModelAndView( "personJSP");
}
If you start coding JSP using EL without first learning the basics, the original old way of doing things, you will be forever confused. EL's ${} looks kind of like jquery's $() operator, but it is not.
The EL expression
${personList[0].NContrato}
is equivalent to
<%= personList[0].NContrato %>
or
<% out.print( personList[0].NContrato ); %>
It runs on the server side and prints the value of personList[0].NContrato into the HTML source you are building.
The expression
${personList[' + ind + '].NContrato}
does nothing. Why? Because ${} runs on the server and only prints variables. There is no variable named "personList[' + ind + '].NContrato". That exact text "${personList[' + ind + '].NContrato}" will be printed into your HTML source. Hence the importance of viewing the source in the browser when troubleshooting.
As for
${newPerson=personList[0]};
you can't do an assignment like that in EL. Ask yourself if the following would make any sense at all?
<% out.print( newPerson=personList[0] ); %>
It doesn't make sense to do an assignment inside a print command.

Categories